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

Dictionary 如何使用Swift访问通过NSNotification传递的词典,dictionary,notifications,swift,Dictionary,Notifications,Swift,我有发送通知的代码(其中serialNumber是字符串): 我尝试了多种代码来实现这一点,但没有成功: let dict = notification.userInfo let dict: Dictionary<String, String> = notification.userInfo let dict: Dictionary = notification.userInfo as Dictionary 所以问题是:如何编写Swift代码来提取通过通知传递的对象,在本例中是一个

我有发送通知的代码(其中serialNumber是字符串):

我尝试了多种代码来实现这一点,但没有成功:

let dict = notification.userInfo
let dict: Dictionary<String, String> = notification.userInfo
let dict: Dictionary = notification.userInfo as Dictionary

所以问题是:如何编写Swift代码来提取通过通知传递的对象,在本例中是一个字典,并访问该对象的组成部分(在本例中是键和值)

As notification.userInfo类型是AnyObject a您必须将其向下转换为相应的字典类型

在知道字典的确切类型后,您不需要对从中获得的值进行向下转换。但在使用这些值之前,您可能需要检查字典中是否实际存在这些值:

// 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")
}
//首先尝试将用户信息强制转换为预期类型
如果let info=notification.userInfo as?字典{
//使用前检查是否存在该值
如果让s=info[“方向”]{
印刷品
}
否则{
打印(“键没有值\n”)
}
}
否则{
打印(“错误的用户信息类型”)
}

您应该使用类似于
[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
}

总是点击打印(“错误的用户信息类型”)-在swift中2@Async-它在操场上对我有用。但是,您需要确保所有键和值都是字符串。如果您有不同的类型,您将需要在第1个cast中更改类型对不起,是的,它工作-重置模拟器内容后,清理并构建它工作!很好!谢谢。在4.9.19中,“UNNotification”类型的值没有成员“userInfo”
let sn : String = dict["Identity"]!
let sn : String = dict.valueForKey("Identity") as String
let sn : String = dict.valueForKey("Identity")
// 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")
}
func keyboardWillShown(notification : NSNotification){
    let tmp : [NSObject : AnyObject] = notification.userInfo!
    let duration : NSNumber = tmp[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
    let scalarDuration : Double = duration.doubleValue
}