如何使用Swift访问通过NSNotification传递的Dictionary

use*_*657 37 notifications dictionary swift

我有发送通知的代码(其中serialNumber是一个String):

  var dataDict = Dictionary<String, String>()
  dataDict["Identity"] = serialNumber
  dataDict["Direction"] = "Add"
            NSNotificationCenter.defaultCenter().postNotificationName("deviceActivity", object:self, userInfo:dataDict)
Run Code Online (Sandbox Code Playgroud)

接收此通知的代码:

  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
  }
Run Code Online (Sandbox Code Playgroud)

我尝试了各种代码来实现这一目标,但没有成功:

let dict = notification.userInfo
let dict: Dictionary<String, String> = notification.userInfo
let dict: Dictionary = notification.userInfo as Dictionary
Run Code Online (Sandbox Code Playgroud)

虽然我的一些尝试满足编译器,但在尝试访问已提取为Dictionary的内容时,没有人产生实际的字符串:

let sn : String = dict["Identity"]!
let sn : String = dict.valueForKey("Identity") as String
let sn : String = dict.valueForKey("Identity")
Run Code Online (Sandbox Code Playgroud)

所以问题是这样的:我如何编写Swift代码来提取一个对象,在本例中是一个通过通知传递的Dictionary,并访问该对象的组成部分(在这种情况下是键和值)?

Vla*_*mir 40

由于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")
}
Run Code Online (Sandbox Code Playgroud)


Ole*_*nko 12

你应该使用类似结构[NSObject : AnyObject]并从NSDictionary中检索值yourLet[key]

func keyboardWillShown(notification : NSNotification){
    let tmp : [NSObject : AnyObject] = notification.userInfo!
    let duration : NSNumber = tmp[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
    let scalarDuration : Double = duration.doubleValue
}
Run Code Online (Sandbox Code Playgroud)