Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift property - getter ivar

Tags:

getter

swift

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()
    }
}
like image 825
Adam Carter Avatar asked Sep 14 '14 00:09

Adam Carter


Video Answer


3 Answers

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.

like image 129
Jack Lawrence Avatar answered Oct 17 '22 13:10

Jack Lawrence


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

like image 36
Antonio Avatar answered Oct 17 '22 12:10

Antonio


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()
    }
}
like image 4
Anthony Kong Avatar answered Oct 17 '22 12:10

Anthony Kong