Do something when the dictionary values ​​change

I am looking for a way to run some code whenever the values ​​of the dictionary change. I'm still 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 compilation error (using an unresolved identifier something) and whatever I do, I cannot get it to work. Any ideas?

+3


source to share


1 answer


What you are looking for is a didSet

property observer . The following is used:

var objects: NSMutableDictionary? {
    didSet {
        // stuff
    }
}

      

Note that willSet

- this is another option if you want to be notified immediately before a property change, not just after that. In case, willSet

you are provided with a variable newValue

representing the incoming property value, and in case didSet

, a property oldValue

representing the outgoing value.



Since @ Paulw11 is below, this will not notify you when the contents of the dictionary have changed. Only when the variable is reassigned. If you want to be notified when values ​​within a dictionary are updated (AFAIK) you should use the equivalent Swift Dictionary.

var swiftObjects: [NSObject: AnyObject]? {
    didSet {
        println(oldValue)
    }
}

      

+6


source







All Articles