Property Observer for Array,获取更改的索引

时间:2018-03-31 11:36:29

标签: ios arrays swift property-observer

我有Array

let myArray = [String]()

我想添加一个didSet { },它知道实际更改的数组索引。

2 个答案:

答案 0 :(得分:0)

你可以试试这个 -

let myArray = [String]()

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

let demo = YourClassName()
demo.array = [1,2,7,7,5]
//  prints:  Changed indexes: [2, 3]

答案 1 :(得分:0)

这将为您提供所有已更改的索引,即使这些数组具有不同的长度:

class TestClass {
    var array: [String] = ["a", "2", "3", "d", "5", "has one more"] {
        didSet {
            var changed = zip(array, oldValue).enumerated().reduce([]) { $1.element.0 == $1.element.1 ? $0 : $0 + [$1.offset] }
            changed.append(Array(min(array.count, oldValue.count)..<max(array.count, oldValue.count)))

            print(changed) // prints: [0, 3, 5]
        }
    }
}

TestClass().array = ["1", "2", "3", "4", "5"]

第一行:

var changed = zip(array, oldValue).enumerated().reduce([]) { $1.element.0 == $1.element.1 ? $0 : $0 + [$1.offset] }

获取所有索引,直到最短数组结束时不同,第二行:

changed.append(Array(min(array.count, oldValue.count)..<max(array.count, oldValue.count)))

附加较长数组的其余索引。