user1898829
user1898829

Reputation: 3517

What should I be returning in a getter method in swift

var userState: UserState {
    get {
        return userState
    }
    set {
        print("\(self.userState)")
    }
}

Returning userState causes an infinite loop. I'm not interested in the getter method and just want to return the value of the property in the getter. I would rather like to customise the setter method.

Upvotes: 5

Views: 2395

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726519

If you would like to override a setter, but keep your property readable, then you need to make a variable to "back" the property:

private var storedUserState: UserState
var userState: UserState {
    get {
        return storedUserState
    }
    set {
        print("Before: \(self.storedUserState)")
        storedUserState = newValue
        print("After: \(self.storedUserState)")
    }
}

If you would like to customize a setter method, but would prefer the property to remain stored, use property observers instead of overriding the accessors:

var userState: UserState = nil {
    willSet(newState) {
        print("About to set userState: \(newState)")
    }
    didSet {
        print("Finished: new=\(userState), old=\(oldValue)")
    }
}

Upvotes: 8

Uncommon
Uncommon

Reputation: 3383

Instead of set, what you want is willSet or didSet, which get run before/after the value changes. Then you can omit get.

With willSet, since the variable hasn't changed yet, the new value is available in a parameter called newValue. Conversely, didSet has oldValue.

Upvotes: 3

Related Questions