[英]unexpectedly found nil while unwrapping an Optional value when accessing dictionary with non-existent key
I'm trying to error handle the userInfo dictionary when receiving a remote push notification, in case the dictionary is missing an expected key. 我试图在接收到远程推送通知时对userInfo字典进行错误处理,以防字典缺少预期的键。 I keep getting an
unexpectedly found nil while unwrapping an Optional value
error when I try to do this: 当我尝试这样做时,
unexpectedly found nil while unwrapping an Optional value
错误时,我总是得到unexpectedly found nil while unwrapping an Optional value
:
if let message = userInfo["key_that_might_not_exist"] as? String {
// do something
}
I thought that if a key does not exist, it would be nil. 我以为如果不存在密钥,它将为零。 What am I doing wrong here?
我在这里做错了什么?
Try 尝试
if let message:String = a["key_that_might_not_exist"] {
// do something
}
First of all, use a String
; 首先,使用
String
; I do not think you need to have that specific thing as an NSString
. 我认为您不需要将特定的东西作为
NSString
。
Second, are you sure userinfo
exists? 其次,您确定
userinfo
存在吗? You could easily be setting the post wrong. 您很容易将帖子设置错了。 Try wrapping it in:
尝试将其包装在:
if let dictionary = userInfo {
}
is your userInfo really not nil? 您的userInfo真的不是nil吗?
if let userInfo = notification.userInfo as? Dictionary<String,NSObject> {
if let message = userInfo["key_that_might_not_exist"] as? NSString {
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.