我知道如何初始化一个不带参数的闭包,如下所示:
class testClass {
var myClosure: () -> ()
init(){
myClosure = {}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我无法弄清楚如何初始化闭包:
var myClosure: (Int) -> ()
Run Code Online (Sandbox Code Playgroud)
我怎么做?
类型的闭包(Int) -> ()需要一个参数(Swift会告诉你,不能隐式忽略该参数).
因此,如果您想要一个带有一个参数的闭包,则必须明确指定:
let myClosure: (Int) -> () = { parameter in }
Run Code Online (Sandbox Code Playgroud)
(如果您不需要参数,可以用通配符替换它来忽略它)
let myClosure: (Int) -> () = { _ in }
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用隐式参数($0,$1等),但它们仅在闭包中某处使用参数时才起作用(例如,通过将其分配给另一个变量或将其作为参数传递给函数):
let myClosure: (Int) -> () = { print($0) }
Run Code Online (Sandbox Code Playgroud)
简单的例子:
class TestClass {
var myClosure: (Int) -> ()
init(){
func myFunc(_:Int) {}
self.myClosure = myFunc
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用匿名函数:
class TestClass {
var myClosure: (Int) -> ()
init(){
self.myClosure = {_ in}
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果声明如下,您可以将初始化作为一部分myClosure:
class TestClass {
var myClosure : (Int) -> () = {_ in}
init(){
}
}
Run Code Online (Sandbox Code Playgroud)
但是如果你没有myClosure初始化时的值,为什么不把它变成一个可选的呢?
class TestClass {
var myClosure: ((Int) -> ())?
init(){
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2008 次 |
| 最近记录: |