简体   繁体   English

数组的属性观察器,获取更改的索引

[英]Property Observer for Array, that gets the changed index

I have an Array : 我有一个Array

let myArray = [String]()

And I would like to add a didSet { } , that is aware of the array index that was actually changed. 我想添加一个didSet { } ,它知道实际更改的数组索引。

You can try this - 你可以试试这个-

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]

This will give you all the indexes that changed, even if the arrays have different length: 这将为您提供所有已更改的索引,即使数组的长度不同:

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"]

The first line: 第一行:

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

gets you all indexes that are different until the end of the shortest array, and the second line: 获取所有不同的索引,直到最短数组的末尾,第二行:

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

appends the remaining indexes of the longer array. 追加较长数组的其余索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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