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

我有代码发送通知(其中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,因此您必须将其下转换为适当的字典类型。

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

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...