简体   繁体   中英

Dictionary getting nil value due that app is crashing. Unexpectedly found nil while unwrapping an optional value

I've a property named as messageDict sometimes it will get nil value due to that app is crashing. can someone suggest me how to properly handle it.

 var messageDict : [String : NSArray]?

if let messageDict = messageDict {
    let messageArray = messageDict[outBoxId]! as! [MCOIMAPMessage] // crash indicates here
}

If the data is availabe i will store below data. sometimes it will be nil

Message-ID: CABQG1ZJT0a7=NExme6VWA6iRpe6Du5LViuA9kZf-QbqOyX1RfQ@mail.gmail.com

References: [dca79b0a-ea55-a4f6-aef3-9097559148f5@peoplelogic.in,CABQG1ZKpat9nGSOjs-Q341bmn0vkiVH+CdFpu2JgkC92KO_K=Q@mail.gmail.com]

In-Reply-To: [CABQG1ZKpat9nGSOjs-Q341bmn0vkiVH+CdFpu2JgkC92KO_K=Q@mail.gmail.com]

Don't force unwrap it, try to check if there is something first

if let messageDict = messageDict, let messageArray = messageDict[outBoxId] as? [MCOIMAPMessage] {
}

Unwrap with guard/if will be safe.

var messageDict : [String : NSArray]?

guard let message = messageDict else {
    return
}
guard let messageArray = message[outBoxId] as? [MCOIMAPMessage] else {
    return
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM