假设我有一个数组:
var intArray: [Int] = [1,2,3,4,5] {
didSet{
//print index of value that was modified
}
}
如果我intArray[2] = 10
,我可以在didSet
内写什么来打印修改后的值的索引(在本例中为2)?
答案 0 :(得分:5)
zip()函数可能对此有用:
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]
它也适用于单个元素更改,但是数组会受到多个更改,因此更安全地获取更改的索引数组。