0

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

1 Answers1

4

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]
Jaydeep Vora
  • 6,085
  • 1
  • 22
  • 40
  • 3
    `didSet` observers have an implicit `oldValue` variable, there is no need for your `oldArray` – Martin R Aug 17 '17 at 05:41
  • If I had an array: [1, 2, ["a", "b", "c"], 3] and did array[3][2] = "e", would your code return [3][2]. I'm pretty sure it would, but just for clarification? – Lachlan Walls Aug 17 '17 at 05:45