Daniel
Daniel

Reputation: 7714

Swift didSet get index of array

Suppose I have an array:

var intArray: [Int] = [1,2,3,4,5] {
    didSet{
        //print index of value that was modified
    }
}

if I do intArray[2] = 10, what can I write inside didSet in order to print the index of the modified value (2, in this case) ?

Upvotes: 3

Views: 1369

Answers (1)

Alain T.
Alain T.

Reputation: 42133

The zip() function could be useful for this:

class A
{
   var array = [1,2,3,4,5]
   {
     didSet 
     { 
        let changedIndexes = zip(array, oldValue).map{$0 != $1}.enumerated().filter{$1}.map{$0.0}
        print("Changed indexes: \(changedIndexes)")
     }
   }
}

let a = A()
a.array = [1,2,7,7,5]

//  prints:  Changed indexes: [2, 3]

It also works for single element changes but arrays are subject to multiple changes so its safer to get an array of changed indexes.

Upvotes: 8

Related Questions