Moody
Moody

Reputation: 352

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

Upvotes: 0

Views: 186

Answers (2)

Suresh Kumar Durairaj
Suresh Kumar Durairaj

Reputation: 2126

The method updateValue on dictionary returns the value that has been replaced. So when you do

if let oldItem = shoppingList.updateValue("honey", forKey: "item2")

The replaced value which is milk is returned to the oldItem.

println("old value was \(oldItem)")

oldItem returns the old value it posses.

Note: When you do updateValue on dictionary, the new key/value pair is updated if the key is presented. If the key is not presented then the new key/value pair is added to the dictionary. And the updateValue returns the old updated value if the key is exists and returns nil if not.

Upvotes: 1

Dejan Skledar
Dejan Skledar

Reputation: 11435

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.

Upvotes: 1

Related Questions