美文网首页
[Swift] 什么时候该用 unowned

[Swift] 什么时候该用 unowned

作者: CharlesQiu | 来源:发表于2018-01-11 15:05 被阅读59次
  • 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 里面的闭包捕获了selfself永远不会为nil

class RetainCycle {
    var closure: (() -> Void)!
    var string = "Hello"
    init() {
        closure = { [unowned self] in
            self.string = "Hello, World!"
        }
    }
} 

在这个例子中,由于我们在初始化RetainCycle类后立即调用了闭包,所以我们可以认为self永远不会为nil

相关文章

网友评论

      本文标题:[Swift] 什么时候该用 unowned

      本文链接:https://www.haomeiwen.com/subject/qoutbxtx.html