简体   繁体   中英

Property Observer for Array, that gets the changed index

I have an Array :

let myArray = [String]()

And I would like to add a didSet { } , that is aware of the array index that was actually changed.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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