Optional("var") in println
Asked Answered
G

1

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?

Gentian answered 25/8, 2014 at 11:26 Comment(1)
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?Advisory
G
12

oki just need to add a "!"

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

Gentian answered 25/8, 2014 at 11:32 Comment(1)
This will crash if stringForKey() returns nil, i.e. "if the default does not exist or is not a string or number value"Cerargyrite

© 2022 - 2024 — McMap. All rights reserved.