Observers of ownership of dictionaries at Swift

I want to call a delegate method when a new item is added to my dictionary. For properties with a single value, the observer didSet(newValue)

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)")
}

      

}

Exit from willSet(newUser)

:

[3E33BD4D-6F48-47FC-8612-565250126E51 will be installed: User: userId: Optional ("3E33BD4D-6F48-47FC-8612-565250126E51"), listenerUUID: Optional ("77D01D6F-D017-EF85250126E51 : nil]

As more items are added, it newUser

just contains the entire dictionary.

How can I get the handle of just added new item?

+3


source to share


3 answers


There is no easy way to do this. Dictionary

is not a class. You cannot override your functions and observe properties. Here's an example with an array-like object that can watch when elements are added, removed, etc. Get notified when an item is added / removed to an array



0


source


The easiest way is to use indexes, which provide a flexible way of assigning key index values, allowing code to be processed before and after updates to the dictionary or the internal structure of an object. For more information on subscript check the following link:

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



I've included some sample 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

      

+4


source


If you can calculate the difference between the two dictionaries, you can remember the previous state of your dictionary. When triggered willSet

(or didSet

), you can calculate the difference between the previous state of your dictionary and the new state. The difference is your change, eg. items removed or added.

0


source







All Articles