Shorthand setter declaration for a subscript of an array in Swift

后端 未结 2 1096
死守一世寂寞
死守一世寂寞 2021-01-25 18:41

In my last question, I asked how to write setter for a subscript of a computed property in Swift. I think my question was not substantial enough to be understood. The answer giv

相关标签:
2条回答
  • 2021-01-25 19:13

    What you're not understanding is that an ordinary setter is the shorthand you are looking for. If an object has an array property and someone sets into that array, the setter is called.

    For example:

    class Thing {
        var arr : [Int] = [1, 2, 3] {
            didSet {
                println("I saw that")
            }
        }
    }
    
    var t = Thing()
    t.arr[1] = 100 // "I saw that"
    

    So all you have to do is use didSet to compare the new value to the old value and respond however you like to the change.

    0 讨论(0)
  • 2021-01-25 19:22

    I did think of another way, but I don't like it much. Use an extension to add another subscript to setter to Array - a setter that allows you to supply a callback. The problem with this approach is that you have remember to supply the callback! This puts the onus on whoever sets into the index, which is probably not what you had in mind. Still, it has the advantage, once configured, of brevity - and it takes O(0) time:

    extension Array {
        subscript(ix:Int, f:(T,T,Int)->Void) -> T {
            set {
                let old = self[ix]
                self[ix] = newValue
                f(old,newValue,ix)
            }
            get {
                return self[ix]
            }
        }
    }
    
    class Thing {
        var arr : [Int] = [1, 2, 3]
        func f (oldv:Int, newv:Int, ix:Int) {
            println("changed \(oldv) to \(newv) at \(ix)")
        }
    }
    
    var t = Thing()
    t.arr[1,t.f] = 100 // "changed 2 to 100 at 1"
    
    0 讨论(0)
提交回复
热议问题