Woogie
Woogie

Reputation: 105

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. I keep getting an unexpectedly found nil while unwrapping an Optional value error when I try to do this:

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?

Upvotes: 0

Views: 306

Answers (3)

Michael Voznesensky
Michael Voznesensky

Reputation: 1618

First of all, use a String; I do not think you need to have that specific thing as an NSString.

Second, are you sure userinfo exists? You could easily be setting the post wrong. Try wrapping it in:

if let dictionary = userInfo {

}

Upvotes: 0

theguy
theguy

Reputation: 1252

is your userInfo really not nil?

if let userInfo = notification.userInfo as? Dictionary<String,NSObject> {
    if let message = userInfo["key_that_might_not_exist"] as? NSString {
        ...
    }
}

Upvotes: 0

qwerty_so
qwerty_so

Reputation: 36313

Try

 if let message:String = a["key_that_might_not_exist"]  {
    // do something
 }

Upvotes: 1

Related Questions