Swift如何设置闭包类型中的参数可有可无
在Swift中,可以使用闭包类型的参数设置为可选类型(Optional)来实现参数可有可无的效果。具体做法是使用问号(?)将参数类型声明为可选类型。
例如,假设有一个闭包类型的参数,参数类型为Int:
let closure: ((Int?) -> Void) = { number in
if let number = number {
print("The number is \(number).")
} else {
print("No number provided.")
}
}
closure(10) // 输出:The number is 10.
closure(nil) // 输出:No number provided.
在上述代码中,闭包类型的参数number的类型为Int?,即可选类型的Int。当传入的参数为非空值时,闭包内部会输出该值;当传入的参数为nil时,闭包内部会输出"没有提供数字"。
原文地址: https://www.cveoy.top/t/topic/h7OS 著作权归作者所有。请勿转载和采集!