-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Learning Swift Second Edition
By :

So we know that the purpose of optionals in Swift is to allow the representation of the absence of a value, but what does that look like and how does it work? An optional is a special type that can "wrap" any other type. This means that you can make an optional String
, optional Array
, and so on. You can do this by adding a question mark (?
) to the type name, as shown:
var possibleString: String? var possibleArray: [Int]?
Note that this code does not specify any initial values. This is because all optionals, by default, are set to no value at all. If we want to provide an initial value we can do so similar to any other variable:
var possibleInt: Int? = 10
Also, note that if we left out the type specification (: Int?
), possibleInt
would be inferred to be of type Int
instead of an optional Int
.
Now, it is pretty verbose to say that a variable lacks a value. Instead, if an optional lacks a variable, we say it is nil. So both possibleString
and possibleArray
are nil...
Change the font size
Change margin width
Change background colour