Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I be returning in a getter method in swift

Tags:

swift

swift3

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.

like image 439
user1898829 Avatar asked Mar 03 '17 16:03

user1898829


2 Answers

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)")
    }
}
like image 147
Sergey Kalinichenko Avatar answered Oct 21 '22 22:10

Sergey Kalinichenko


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.

like image 39
Uncommon Avatar answered Oct 21 '22 23:10

Uncommon