简体   繁体   English

使用不存在的键访问字典时,在展开可选值时意外发现nil

[英]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.

相关问题 Dictionary在解包Optional值时意外地发现了nil - Dictionary Unexpectedly found nil while unwrapping an Optional value 展开Optional值时意外发现nil - unexpectedly found nil while unwrapping an Optional value 展开可选的value()时意外找到nil - Unexpectedly found nil while unwrapping an Optional value() 在实际设备上的Glance中访问IBOutlet时,WatchKit“在解开可选值时意外发现nil” - WatchKit “unexpectedly found nil while unwrapping an Optional value” when accessing IBOutlet in Glance on actual device 致命错误:访问URL时,在展开可选值时意外发现nil - fatal error: unexpectedly found nil while unwrapping an Optional value when accessing URL 添加UINavigation时,“在展开可选值时意外发现nil” - “Unexpectedly found nil while unwrapping an Optional value” When UINavigation is added 加载tableView时解开可选值时意外发现nil - Unexpectedly found nil while unwrapping an optional value when loading tableView 展开Optional值时意外发现nil - Unexpectedly found nil when unwrapping an Optional value 由于该应用崩溃,字典获得了零值。 展开可选值时意外找到nil - Dictionary getting nil value due that app is crashing. Unexpectedly found nil while unwrapping an optional value 值不是nil,但是在展开Optional值时意外发现nil - value is not nil but getting unexpectedly found nil while unwrapping an Optional value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM