我应该在swift的getter方法中返回什么

时间:2021-05-05 07:10:17
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.

返回userState会导致无限循环。我对getter方法不感兴趣,只想在getter中返回属性的值。我宁愿自定义setter方法。

2 个解决方案

#1


6  

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

如果您想覆盖一个setter,但保持您的属性可读,那么您需要创建一个变量来“回”该属性:

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:

如果您想自定义setter方法,但希望该属性保持存储,请使用属性观察器而不是覆盖访问器:

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

#2


2  

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

你需要的是willSet或didSet,而不是set,它会在值更改之前/之后运行。然后你可以省略get。

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

使用willSet,由于变量尚未更改,因此新值在名为newValue的参数中可用。相反,didSet有oldValue。

#1


6  

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

如果您想覆盖一个setter,但保持您的属性可读,那么您需要创建一个变量来“回”该属性:

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:

如果您想自定义setter方法,但希望该属性保持存储,请使用属性观察器而不是覆盖访问器:

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

#2


2  

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

你需要的是willSet或didSet,而不是set,它会在值更改之前/之后运行。然后你可以省略get。

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

使用willSet,由于变量尚未更改,因此新值在名为newValue的参数中可用。相反,didSet有oldValue。