Swift property - getter ivar

时光毁灭记忆、已成空白 提交于 2019-12-30 08:13:12

问题


Is there an ivar property we should use in a Swift getter? My code is causing the getter to call the getter until the program crashes:

var document: UIDocument? {
    get {
        return self.document
    }
    set {
        self.document = newValue

        useDocument()
    }
}

回答1:


Swift properties do not have the concept of separate, underlying storage like they do in Objective-C. Instead, you'll need to create a second (private) property and use that as the storage:

private var _document: UIDocument?
var document: UIDocument? {
    get {
        return _document
    }
    set {
        _document = newValue
        useDocument()
    }
}

If all you're trying to do is call useDocument() after the document property is set, you can omit the getter, setter, and private property and instead just use willSet or didSet.




回答2:


If what you are trying to achieve is add some custom processing when the property is set, you don't need to define a separate backing data member and implement a computed property: you can use the willSet and didSet property observers, which are automatically invoked respectively before and after the property has been set.

In your specific case, this is how you should implement your property:

var document: UIDocument? {
    didSet {
        useDocument()
    }
}

Suggested reading: Property Observers




回答3:


In your code there is an infinite recursion situation: for example, self.document inside the getter keep calling the getter itself.

You need to explicitly define an ivar yourself. Here is a possible solution:

private var _document:UIDocument?

var document: UIDocument? {
    get {
        return self._document
    }
    set {
        self._document = newValue

        useDocument()
    }
}


来源:https://stackoverflow.com/questions/25828987/swift-property-getter-ivar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!