Unwrapping optionals

It’s all well and good that optionals exist, but you may be wondering how you can look inside the box and manipulate the value it contains.

Take a look at what happens when you print out the value of an optional:

var result: Int? = 30 print(result)

This prints the following:

Optional(30)

That isn’t really what you wanted — although if you think about it, it makes sense. Your code has printed the box. The result says, “result is an optional that contains the value 30”.

To see how an optional type is different from a non-optional type, see what happens if you try to use result as if it were a normal integer:

print(result + 1)

This code triggers an error:

Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?

It doesn’t work because you’re trying to add an integer to a box — not to the value inside the box, but to the box itself. That doesn’t make sense!

results matching ""

    No results matching ""