-
Apple 官方描述
“Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization.”
翻译:在引用对象的生命周期内,如果它可能为nil
,那么就用weak
引用。反之,当你知道引用对象在初始化后永远都不会为nil
就用unowned
.**
现在你就知道了:就像是implicitly unwrapped optional(隐式可选类型),如果你能保证在使用过程中引用对象不会为nil
,用unowned
。如果不能,那么就用weak
.
下面就是个很好的例子。Class
里面的闭包捕获了self
,self
永远不会为nil
。
class RetainCycle {
var closure: (() -> Void)!
var string = "Hello"
init() {
closure = { [unowned self] in
self.string = "Hello, World!"
}
}
}
在这个例子中,由于我们在初始化RetainCycle
类后立即调用了闭包,所以我们可以认为self
永远不会为nil
。