Lachlan Walls Lachlan Walls - 11 months ago 85
Swift Question

'didSet' certain elements inside Arrays - Swift

I have an array, with multiple values. I want to detect if one of those values is changed, something like this:

var array =
[
1,
2,
3,
4 { didSet{ print("Value Changed")}},
5,
6
]


Is that possible, in any way?

Thanks

Answer Source

Swift 3.0

You can do like below to Observer which index of array is changed.

var oldArray: [Int] = []

var array = [ 1,2,3,4,5,6] {

    willSet {
        // Set old array value for compare
        oldArray = array
    }

    didSet {
        let changedIndex = zip(array, oldArray).map{$0 != $1}.enumerated().filter{$1}.map{$0.0}
        print("index: \(changedIndex)")
    }
}

// Now change value of index 4 of array

array[4] = 10   //index: [4]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download