<Automatic Reference Counting> Apple官方文档传送门
- Defining a Capture List
- Weak and Unowned References
lazy var someClosure: (Int, String) -> String = {
[unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in
// closure body goes here
}
当闭包和它捕获的实例总是相互引用,并且总是在同一时间被释放时,将闭包中的捕获定义为unowned
。
相反,当捕获的引用将来可能变成nil时,将捕获定义为weak
。弱引用总是可选的类型,当它们引用的实例被释放时,它会自动变为nil。这使您能够检查它们是否存在于闭包的主体中。
NOTE
If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference.
"闭包" 和 "其所捕获的实例" 的生命周期的长短对比来决定用 weak
还是unowned