我想在将新项目添加到我的字典时调用委托(delegate)方法。
对于单值属性,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)
的输出是:
Will set [3E33BD4D-6F48-47FC-8612-565250126E51: User: userId: Optional("3E33BD4D-6F48-47FC-8612-565250126E51"), listenerUUID: Optional("77D01D6F-D017-EF9E-55A9-78570E455C51"), beaconUUID: nil]
随着更多项目的添加,newUser
只包含整个字典。
我怎样才能只处理添加的新项目?
最佳答案
最简单的方法是使用下标,这些提供了一种灵活的方式来分配键下标值,允许代码在更新字典或内部对象结构之前和之后进行处理。有关下标的更多信息,请查看以下链接:
我提供了一些示例代码来提供帮助。
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
关于ios - Swift 字典中的属性观察器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27357935/