Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 didSet(newValue) 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")
    self.delegate.didAddUser(newUser)
} 
willSet(newUser) {
  println("Will set \(newUser)")
}

}

The output from willSet(newUser) is:

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 newUser simply contains the entire dictionary.

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

like image 626
Morten Avatar asked Dec 02 '25 14:12

Morten


1 Answers

The easiest way is to use subscripts, these provide a flexible way to assign keys subscript values, allowing code process before and after updates to a dictionary or internal object structure. For more information regarding subscripts checkout the following link:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html

I've included some example code to help.

class User {
    var userId:String = NSUUID.init().UUIDString
    var name:String = "Your Users Name"
}

class UserDictionary {
    var users = [String:User]()
    subscript(userId:String) -> User? {
        get {
            return users[userId]
        } set {
            // if newValue is nil then you are about to remove user
            users[userId] = newValue
            // do after value processing.
            print("[\(userId)]=\(newValue)")
        }
    }
}

var userdict = UserDictionary()
let user = User()
userdict[user.userId] = user
like image 192
Steven Wilson Avatar answered Dec 05 '25 07:12

Steven Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!