Swift didSet get index of array

2019-02-11 07:33发布

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

标签: swift swift3
1条回答
啃猪蹄的小仙女
2楼-- · 2019-02-11 07:36

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.

查看更多
登录 后发表回答