Adam Carter
Adam Carter

Reputation: 4844

Swift property - getter ivar

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()
    }
}

Upvotes: 11

Views: 10898

Answers (3)

Antonio
Antonio

Reputation: 72750

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

Upvotes: 10

Anthony Kong
Anthony Kong

Reputation: 40624

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()
    }
}

Upvotes: 4

Jack Lawrence
Jack Lawrence

Reputation: 10772

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.

Upvotes: 24

Related Questions