1
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

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Riya Khanna
  • 246
  • 1
  • 3
  • 9
  • 2
    Why it is downvoted ? – Riya Khanna May 28 '15 at 07:57
  • 5
    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 May 28 '15 at 08:00
  • 2
    @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 May 28 '15 at 08:18
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Cristik Mar 19 '18 at 06:01

3 Answers3

9

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)
}
Tariq
  • 9,861
  • 12
  • 62
  • 103
  • 5
    Downvoters, care to comment. Whats wrong with the solution? Being a 6 years of active member on stackoverflow I know its so easy to click downvote button, but don't ever to do that without proper comments. – Tariq May 30 '15 at 07:29
  • For your comment and answer you get one UPvote - I agree, people are here to learn, and noobs (like myself) get put off when people downvote. We just need a little guidance is all.. – JamesG Feb 29 '16 at 10:25
8

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") ?? ""
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
1

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

Marius Fanu
  • 6,589
  • 1
  • 17
  • 19