如何访问通过NSNotification传递的字典,使用Swift

如何访问通过NSNotification传递的字典,使用Swift,第1张

概述我有代码发送通知(其中serialNumber是一个字符串): var dataDict = Dictionary<String, String>() dataDict["Identity"] = serialNumber dataDict["Direction"] = "Add" NSNotificationCenter.defaultCenter().postN 我有代码发送通知(其中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.userInfolet dict: Dictionary<String,String> = notification.userInfolet dict: Dictionary = notification.userInfo as Dictionary

虽然我的一些尝试满足编译器,没有一个产生实际的字符串时,试图访问已提取的字典

let sn : String = dict["IDentity"]!let sn : String = dict.valueForKey("IDentity") as Stringlet sn : String = dict.valueForKey("IDentity")

所以问题是这样:我如何写Swift代码提取一个对象,在这种情况下一个字典,通过通知,并访问该对象的组件部分(在这种情况下的键和值)?

由于notification.userInfo类型是AnyObject,因此您必须将其下转换为适当的字典类型。

在知道确切类型的字典后,你不需要从它得到的downcast值。但是,在使用它们之前,您可能想要检查值是否实际存在于字典中:

// First try to cast user info to expected typeif 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")}
总结

以上是内存溢出为你收集整理的如何访问通过NSNotification传递的字典,使用Swift全部内容,希望文章能够帮你解决如何访问通过NSNotification传递的字典,使用Swift所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1056725.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存