Introducing optionals

Optionals are Swift’s solution to the problem of representing both a value and the absence of a value. An optional type is allowed to reference either a value or nil.

Think of an optional as a box: it either contains a value, or it doesn’t. When it doesn’t contain a value, it’s said to contain nil. The box itself always exists; it’s always there for you to open and look inside.

A string or an integer, on the other hand, doesn’t have this box around it. Instead there’s always a value, such as "hello" or 42. Remember, non-optional types are guaranteed to have an actual value.

Note: Those of you who’ve studied physics may be thinking about Schrödinger’s cat right now. Optionals are a little bit like that, except it’s not a matter of life and death!

You declare a variable of an optional type by using the following syntax:

var errorCode: Int?

The only difference between this and a standard declaration is the question mark at the end of the type. In this case, errorCode is an “optional Int”. This means the variable itself is like a box containing either an Int or nil.

Note: You can add a question mark after any type to create an optional type. This optional type is said to wrap the regular non-optional type. For example, optional type String? wraps type String. In other words: an optional box of type String? holds either a String or nil.

Also, note how an optional type must be made explicit using a type annotation (here : Int?). Optional types can never be inferred from initialization values, as those values are of a regular, non-optional type, or nil, which can be used with any optional type.

Setting the value is simple. You can either set it to an Int, like so:

errorCode = 100

Or you can set it to nil, like so:

errorCode = nil

This diagram may help you visualize what’s happening:

The optional box always exists. When you assign 100 to the variable, you’re filling the box with the value. When you assign nil to the variable, you’re emptying the box.

Take a few minutes to think about this concept. The box analogy will be a big help as you go through the rest of the chapter and begin to use optionals.

results matching ""

    No results matching ""