Search code examples
iosswiftoption-typeswift-playground

Optionals in Swift, why this simple code doesn't print optional?


var shoppingList = ["item1": "bread", "item2": "milk" ]

if let oldItem = shoppingList.updateValue("honey", forKey: "item2") {
    println("old value was \(oldItem)")
}

// This prints out "old value was milk"

However, if I do this

var shoppingList = ["item1": "bread", "item2": "milk" ]

let oldItem = shoppingList.updateValue("honey", forKey: "item2")
println("old value was \(oldItem)")
// This would print out "old value was Optional("milk")

if oldItem != nil {
   println("old value was \(oldItem)")
}

// And this prints out the same "old value was Optional("milk")

Why is that happening here and not in the if statement in the first example?

NOTE: I am testing this in playground, Version 6.1.1 (6A2008a).


Solution

  • var shoppingList = ["item1": "bread", "item2": "milk" ]
    
    if let oldItem = shoppingList.updateValue("honey", forKey: "item2") {
        println("old value was \(oldItem)")
    }
    
    // This prints out "old value was milk"
    

    Because this code (the if let statment) unwraps the value for key "item2", and stores the unwraped value in oldItem.

    If you'd just print it like this:

    let oldItem = shoppingList.updateValue("honey", forKey: "item2")
    println("old value was \(oldItem)")
    

    It would print Optional("old value was milk")

    But if there wouldn't be any value for the key item2, then the program would crash.