5

I got the Problem if i try print a var i sometimes get a "Optional("var")" if i try log it or print it to a lable, but else when i dont get it.

See here

ViewController.swift

import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        NSUserDefaults.standardUserDefaults().setObject("notWorking", forKey: "testvar")
        NSUserDefaults.standardUserDefaults().synchronize()
        println(NSUserDefaults.standardUserDefaults().stringForKey("testvar"))
        var test = "working"
        println(test)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Anyone can explain when this "Optional" appears and what its use for? How can i remove it?

Fabian Boulegue
  • 6,476
  • 14
  • 47
  • 72
  • Hi, I am also interested as to why `Optional` it is appearing if a `!` doesn't follow the variable name. Did you ever come to a solution? – AnchovyLegend Apr 06 '15 at 23:47

1 Answers1

12

oki just need to add a "!"

println(NSUserDefaults.standardUserDefaults().stringForKey("testvar")!)

Fabian Boulegue
  • 6,476
  • 14
  • 47
  • 72
  • This will crash if `stringForKey()` returns nil, i.e. "if the default does not exist or is not a string or number value" – RyanM Apr 27 '15 at 18:29