1
votes
var session = NSUserDefaults.standardUserDefaults().stringForKey("session")!
println(session)

I am getting crash with following error:

fatal error: unexpectedly found nil while unwrapping an Optional value

3
Why it is downvoted ? - Riya Khanna
There are 430 search results for [swift] "unexpectedly found nil while unwrapping an Optional value" and 6 results for [swift] NSUserDefaults "unexpectedly found nil while unwrapping an Optional value" – Are you sure that none of them solves your problem? - Martin R
@MartinR Yeah I saw few search results and everyone has posted entire source code. Being a fresher its impossible to go through hundreds of line of code to figure out my issue. - Riya Khanna

3 Answers

9
votes

You're getting crash due to the forced unwrapping operator ! which is attempting to force unwrap a value from a nil optional.

The forced unwrapping operator should be used only when an optional is known to contain a non-nil value.

You can use optional binding:

if let session = NSUserDefaults.standardUserDefaults().stringForKey("session") {
    printString(session)
}
8
votes

you should use the nil coalescing operator "??"

let session = NSUserDefaults.standardUserDefaults().stringForKey("session") ?? ""

Xcode 8.2 • Swift 3.0.2

let session = UserDefaults.standard.string(forKey: "session") ?? ""
1
votes

You need to remove the ! at the end or you need to check before you unwrap if like this:

If there is a value at that location put in the session constant and execute the block of the if, if not skip the if block

if let session = NSUserDefaults.standardUserDefaults().stringForKey("session") {
    println(session)
}

You should take a look over the Swift documentation regarding Optional type here