Riya Khanna
Riya Khanna

Reputation: 256

Swift: unexpectedly found nil while unwrapping an Optional value

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

Upvotes: 1

Views: 6731

Answers (3)

Leo Dabus
Leo Dabus

Reputation: 236260

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") ?? ""

Upvotes: 8

Tariq
Tariq

Reputation: 9979

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)
}

Upvotes: 9

Marius Fanu
Marius Fanu

Reputation: 6669

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

Upvotes: 1

Related Questions