Boo*_*oon -1 parameters closures swift swift2
在 Swift 中,如何创建一个包含捕获列表和参数的闭包?
我使用过以任何一种形式呈现的代码,但不知道如何创建具有参数和捕获列表的闭包。
例如
关闭参数列表:
myFunction {
(x: Int, y: Int) -> Int in
return x + y
}
Run Code Online (Sandbox Code Playgroud)
关闭捕获列表:
myFunction { [weak parent = self.parent] in print(parent!.title) }
Run Code Online (Sandbox Code Playgroud)
使用捕获列表的示例尝试:
class MyTest {
var value:Int = 3
func myFunction(f: (x:Int, y:Int) -> Int) {
print(f(x: self.value, y: 5))
}
func testFunction() {
myFunction {
[weak self] (x, y) in //<--- This won't work, how to specify weak self here?
print(self.value)
return self.value + y
}
}
}
Run Code Online (Sandbox Code Playgroud)
你给出的例子确实有效。要同时指定参数列表和捕获列表,您只需执行以下操作:
exampleFunctionThatTakesClosure() { [weak self] thing1, thing2 in
}
Run Code Online (Sandbox Code Playgroud)
但是,通过参数列表创建弱引用意味着self在您的闭包中成为可选的 - 因此,您必须先解包(或强制解包)它才能使用它的值。
例如,强制展开:
func testFunction() {
myFunction {
[weak self] (x, y) in
print(self!.value)
return self!.value + y
}
}
Run Code Online (Sandbox Code Playgroud)
或者:
func testFunction() {
myFunction {
[weak self] (x, y) in
if let weakSelf = self {
print(weakSelf.value)
return weakSelf.value + y
} else {
return y
}
}
}
Run Code Online (Sandbox Code Playgroud)