What is an "unwrapped value" in Swift?

The existing correct answer is great, but I found that for me to understand this fully, I needed a good analogy, since this is a very abstract and weird concept.

So, let me help those fellow "right-brained" (visual thinking) developers out by giving a different perspective in addition to the correct answer. Here is a good analogy that helped me a lot.

Birthday Present Wrapping Analogy

Think of optionals as being like birthday presents that come in stiff, hard, colored wrapping.

You don't know if there's anything inside the wrapping until you unwrap the present — maybe there is nothing at all inside! If there is something inside, it could be yet another present, which is also wrapped, and which also might contain nothing. You might even unwrap 100 nested presents to finally discover there was nothing but wrapping.

If the value of the optional is not nil, now you have revealed a box containing something. But, especially if the value is not explicitly typed and is a variable and not a predefined constant, then you may still need to open the box before you can know anything specific about what's in the box, like what type it is, or what the actual value is.

What's In The Box?! Analogy

Even after you unwrap the variable, you are still like Brad Pitt in the last scene in SE7EN (warning: spoilers and very R-rated foul language and violence), because even after you have unwrapped the present, you are in the following situation: you now have nil, or a box containing something (but you don't know what).

You might know the type of the something. For example, if you declared the variable as being type, [Int:Any?], then you'd know you had a (potentially empty) Dictionary with integer subscripts that yield wrapped contents of any old type.

That is why dealing with collection types (Dictionaries and Arrays) in Swift can get kind of hairy.

Case in point:

typealias presentType = [Int:Any?]

func wrap(i:Int, gift:Any?) -> presentType? {
    if(i != 0) {
        let box : presentType = [i:wrap(i-1,gift:gift)]
        return box
    }
    else {
        let box = [i:gift]
        return box
    }
}

func getGift() -> String? {
    return "foobar"
}

let f00 = wrap(10,gift:getGift())

//Now we have to unwrap f00, unwrap its entry, then force cast it into the type we hope it is, and then repeat this in nested fashion until we get to the final value.

var b4r = (((((((((((f00![10]! as! [Int:Any?])[9]! as! [Int:Any?])[8]! as! [Int:Any?])[7]! as! [Int:Any?])[6]! as! [Int:Any?])[5]! as! [Int:Any?])[4]! as! [Int:Any?])[3]! as! [Int:Any?])[2]! as! [Int:Any?])[1]! as! [Int:Any?])[0])

//Now we have to DOUBLE UNWRAP the final value (because, remember, getGift returns an optional) AND force cast it to the type we hope it is

let asdf : String = b4r!! as! String

print(asdf)

First, you have to understand what an Optional type is. An optional type basically means that the variable can be nil.

Example:

var canBeNil : Int? = 4
canBeNil = nil

The question mark indicates the fact that canBeNil can be nil.

This would not work:

var cantBeNil : Int = 4
cantBeNil = nil // can't do this

To get the value from your variable if it is optional, you have to unwrap it. This just means putting an exclamation point at the end.

var canBeNil : Int? = 4
println(canBeNil!)

Your code should look like this:

let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") 
let sideLength = optionalSquare!.sideLength

A sidenote:

You can also declare optionals to automatically unwrap by using an exclamation mark instead of a question mark.

Example:

var canBeNil : Int! = 4
print(canBeNil) // no unwrapping needed

So an alternative way to fix your code is:

let optionalSquare: Square! = Square(sideLength: 2.5, name: "optional square") 
let sideLength = optionalSquare.sideLength

EDIT:

The difference that you're seeing is exactly the symptom of the fact that the optional value is wrapped. There is another layer on top of it. The unwrapped version just shows the straight object because it is, well, unwrapped.

A quick playground comparison:

playground

In the first and second cases, the object is not being automatically unwrapped, so you see two "layers" ({{...}}), whereas in the third case, you see only one layer ({...}) because the object is being automatically unwrapped.

The difference between the first case and the second two cases is that the second two cases will give you a runtime error if optionalSquare is set to nil. Using the syntax in the first case, you can do something like this:

if let sideLength = optionalSquare?.sideLength {
    println("sideLength is not nil")
} else {
    println("sidelength is nil")
}

Tags:

Ios

Swift

Ios8