I'm looking for a way to run some code whenever the values of a dictionary changes. I'm still quite new to Swift, but this is what I have so far:
var objects: NSMutableDictionary {
didChange(changeKind: keyValue, valuesAtIndexes: indexes, forKey: something){
}
}
This however gives me a compiling error (Use of unresolved identifier something), and whatever I do, I can't seem to make it work. Any ideas?
Change elements in a dictionaryWe can change the value of an item by accessing the key using square brackets ([]). To modify multiple values at once, we can use the . update() method, since this function overwrites existing keys.
In Python, you can add a new item to the dictionary dict with dict_object[key] = new_value . In this way, if the key already exists, the value is updated (overwritten) with the new value.
Change Dictionary Values in Python by Unpacking Dictionary Using the * Operator. In this method, we can change the dictionary values by unpacking the dictionary using the * operator and then adding the one or more key-value pairs we want to change the dictionary.
Avoiding KeyError when accessing Dictionary Key We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned. We can also specify a default value to return when the key is missing.
What you're looking for is the didSet
property observer. Usage is as follows:
var objects: NSMutableDictionary? {
didSet {
// stuff
}
}
Note that willSet
is another option if you want to be notified just before the property changes instead of just after. In the case of willSet
, you're given a newValue
variable representing the incoming value of the property and in the case of didSet
, an oldValue
property representing the outgoing value.
As @Paulw11 brought up below, this will not notify you when the contents of the dictionary change. Only when the variable is reassigned. If you want to be notified whenever the values inside the dictionary are updated, (AFAIK) you have to use an equivalent Swift Dictionary.
var swiftObjects: [NSObject: AnyObject]? {
didSet {
println(oldValue)
}
}
How did you explain this:
class My {
var dict = [String: String]() {
didSet {
print(oldValue)
}
}
}
let my = My()
my.dict["asd"] = "asd"
my.dict["bfg"] = "bfg"
my.dict = [String: String]()
Output:
[:]
["asd": "asd"]
["bfg": "bfg", "asd": "asd"]
So didSet called every time new value added.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With