简体   繁体   中英

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) ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM