斯威夫特词典的财产观察员

时间:2014-12-08 12:22:47

标签: ios swift dictionary

我希望在将新项添加到字典时调用委托方法。 对于单值属性,didSet(newValue)观察者工作正常。但对于我的字典,似乎下面的newUser参数返回完整的字典。

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

}

willSet(newUser)的输出是:

  

将设置[3E33BD4D-6F48-47FC-8612-565250126E51:用户:userId:可选(“3E33BD4D-6F48-47FC-8612-565250126E51”),listenerUUID:可选(“77D01D6F-D017-EF9E-55A9-78570E455C51” ),beaconUUID:nil]

随着更多项目的添加,newUser只包含整个词典。

如何处理添加的新项目?

3 个答案:

答案 0 :(得分:4)

最简单的方法是使用下标,这些方法提供了一种灵活的方式来分配键下标值,允许在更新字典或内部对象结构之前和之后进行代码处理。有关下标的更多信息,请查看以下链接:

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

我已经提供了一些示例代码来提供帮助。

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

答案 1 :(得分:0)

没有简单的方法可以做到这一点。 Dictionary不是一个班级。您无法覆盖其功能并观察属性。下面是一个类似于数组的对象的示例,可以观察何时添加,删除元素等。 Get notified when element added/removed to array

答案 2 :(得分:0)

如果您能够计算两个词典之间的差异,您可以记住词典的先前状态。每当willSet(或didSet)被触发时,您就可以计算字典的先前状态与新状态之间的差异。不同之处在于您的变化,例如:删除或添加元素。