Morten Morten - 5 months ago 40
iOS Question

Property observers on Dictionaries in Swift

I want to call a delegate method when a new item is added to my dictionary.
For single value properties the

observer works fine. But for my dictionary it seems that the newUser argument below returns the full dictionary.

var userIdKeyedDict:Dictionary<String, User> = [:] {
didSet(newUser) {
println("Updating userIdKeyedDict")
willSet(newUser) {
println("Will set \(newUser)")


The output from

Will set [3E33BD4D-6F48-47FC-8612-565250126E51: User: userId: Optional("3E33BD4D-6F48-47FC-8612-565250126E51"), listenerUUID: Optional("77D01D6F-D017-EF9E-55A9-78570E455C51"), beaconUUID: nil]

As more items are added the
simply contains the entire dictionary.

How can I get a handle on just the new item added?


There is no easy way to do it. Dictionary is not a class. You cannot override its functions and observe properties. Here is an example with array-like object that can observe when elements are added, removed, etc. Get notified when element added/removed to array