我有发送通知的代码(其中 serialNumber 是一个字符串):
var dataDict = Dictionary<String, String>()
dataDict["Identity"] = serialNumber
dataDict["Direction"] = "Add"
NSNotificationCenter.defaultCenter().postNotificationName("deviceActivity", object:self, userInfo:dataDict)
接收此通知的代码:
func deviceActivity(notification: NSNotification) {
// This method is invoked when the notification is sent
// The problem is in how to access the Dictionary and pull out the entries
}
我尝试了多种代码来实现这一点,但都没有成功:
let dict = notification.userInfo
let dict: Dictionary<String, String> = notification.userInfo
let dict: Dictionary = notification.userInfo as Dictionary
虽然我的一些尝试满足了编译器的要求,但在尝试访问提取为字典的内容时,没有一个尝试产生实际的字符串:
let sn : String = dict["Identity"]!
let sn : String = dict.valueForKey("Identity") as String
let sn : String = dict.valueForKey("Identity")
所以问题是这样的:我如何编写 Swift 代码来提取通过通知传递的对象(在本例中为字典),并访问该对象的组成部分(在本例中为键和值) ?
最佳答案
由于 notification.userInfo 类型是 AnyObject,因此您必须将其向下转换为适当的字典类型。
在知道确切的字典类型后,您不需要向下转换从中获得的值。但是你可能想在使用它们之前检查值是否确实存在于字典中:
// First try to cast user info to expected type
if let info = notification.userInfo as? Dictionary<String,String> {
// Check if value present before using it
if let s = info["Direction"] {
print(s)
}
else {
print("no value for key\n")
}
}
else {
print("wrong userInfo type")
}
关于dictionary - 如何使用 Swift 访问通过 NSNotification 传递的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24892454/