Swift: how to change a property's value without calling its didSet function

后端 未结 4 478
谎友^
谎友^ 2021-01-01 12:41

How can you set a property\'s value in Swift, without calling its didSet() function outside of an initialization context? The code below was a failed experimen

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 13:08

    If you exactly know when you want to apply side effects just make it explicitly:

    1 Solution:

    func noside(newValue : Int) {
        hoodwink = newValue
    }
    
    func withside(newValue : Int) {
        self.hoodwink = newValue
        toggle = !toggle
    }
    

    2 Solution:

    var toggle : Bool = false
    var hoodwink : Int = 0 
    var hoodwinkToggle: Int {
        get { return hoodwink }
        set(newValue) {
            hoodwink = newValue
            toggle = !toggle
        }
    }
    
    1. func setHoodwinkWithToggle(hoodwink: Int) {...}
    2. ....

    I think these solutions will be more clear and readable, then using one variable which at some calls should have side effects and shouldn't at others.

提交回复
热议问题