本文介绍了Swift didSet获取数组的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组:

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

如果我执行intArray[2] = 10,我可以在didSet里面写什么以打印修改后的值的索引(在这种情况下为2)?

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

推荐答案

zip()函数可能对此有用:

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.

这篇关于Swift didSet获取数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 10:26