Swift - Custom setter on property

半腔热情 提交于 2019-12-28 03:04:13

问题


I am converting a project in to Swift code and have come across an issue in a setter. My Objective-C code looked like this:

- (void)setDocument:(MyDocument *)document
{
    if (![_document isEqual:document]) {
        _document = document;

        [self useDocument];
    }
}

and allowed my View Controller to run this each time the document was set (typically in the prepareForSegue: method of the presenting View Controller).

I have found the property observers willSet and didSet but they only work when the property is being updated, not when it’s initialised and updated.

Any ideas? Thanks

UPDATE

after trying get{} and set{} I get the EXC_BAD_ACCESS error

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

        useDocument()
    }
}

回答1:


You can't use set like that because when you call self.document = newValue you're just calling the setter again; you've created an infinite loop.

What you have to do instead is create a separate property to actually store the value in:

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



回答2:


Here's a Swift 3 version

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


来源:https://stackoverflow.com/questions/25828632/swift-custom-setter-on-property

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