Inspired when answering the question of How do I know if a value of an element inside an array was changed?, The answer was using a Property Observer for checking if an array has been modified.
However, How can I determine what is/are the updated element(s) in a collection type in a property observer? For example:
class MyClass {
var strings: [String] = ["hello", "world", "!"] {
didSet(modifiedStrings) {
print("strings array has been modified!!:")
print(modifiedStrings)
}
}
}
let myClass = MyClass()
myClass.strings.append("a string")
myClass.strings[0] = "Hello"
myClass.strings.removeLast()
Note that the didSet
code has been called for each of adding, updating or deletion operation, but how can I exactly know what are the effected elements? is there even a way to achive this by decalring strings
array as a Property Observer?
I am asking about all collection types in Swift because I assume that it should be the same behavior for all of them, it is about the observing.
Thanks.
You can use the
willSet
observer to calculate changes before they are applied. Like so:Thanks for @hnh, based on his answer, I ended up with:
Execution:
This shows how to deal with array, set and dictionary.