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

标签 dictionary notifications 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,因此您必须将其向下转换为适当的字典类型。

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

// 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/

相关文章:

用于连接字典的键和值的 Pythonic 语法

python - 如何处理AttributeError : 'NoneType' object has no attribute 'get' in big dictionary

bash - bash 命令结束时发出声音

objective-c - 如何在 AppleTV tvOS 的 Siri Remote 上按下 Siri 按钮时暂停 SpriteKit 场景

ios - 标签栏下方的 Swift View 布局

python - 扩展的类似 dict 的子类以支持转换和 JSON 转储而无需额外的

java - 使用 int 作为 java.util.Dictionary 的类型参数

iOS 应用程序无法接收报亭通知

ios - *缺少本地通知的推送通知权利*

swift - 在前台而不是后台接收 Firebase 通知