Ric*_*hiy 2 closures automatic-ref-counting swift unowned-references
I have a function with a completion handler, returning one parameter or more.
In a client, when executing a completion handler, I'd like to have an unowned reference to self, as well as having access to the parameter passed.
Here is the Playground example illustrating the issue and the goal I'm trying to achieve.
import UIKit
struct Struct {
func function(completion: (String) -> ()) {
completion("Boom!")
}
func noArgumentsFunction(completion: () -> Void) {
completion()
}
}
class Class2 {
func execute() {
Struct().noArgumentsFunction { [unowned self] in
//...
}
Struct().function { (string) in // Need [unowned self] here
//...
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如我在评论中所说
Struct().function { [unowned self] (string) in
//your code here
}
Run Code Online (Sandbox Code Playgroud)
捕获应该是关闭顺序的列表和关闭参数,详情请参阅Apple文档
定义捕获列表
捕获列表中的每个项目都是对weak或unown关键字的配对,这些关键字与对类实例(例如self)的引用或以某个值初始化的变量(例如delegate = self.delegate!)的引用。这些配对写在一对方括号内,并用逗号分隔。
将捕获列表放置在闭包的参数列表之前,如果提供,则返回类型:
lazy var someClosure: (Int, String) -> String = {
[unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in
// closure body goes here
}
Run Code Online (Sandbox Code Playgroud)
如果闭包没有指定参数列表或返回类型,因为可以从上下文中推断出它们,则将捕获列表放在闭包的最开始,然后是in关键字:
lazy var someClosure: () -> String = {
[unowned self, weak delegate = self.delegate!] in
// closure body goes here
}
Run Code Online (Sandbox Code Playgroud)