Introducing optionals
So, we know that the purpose of optionals in Swift is to allow the representation of the absent 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:
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 like any other variable:
var possibleInt: Int? = 10
Also note that, if we leave out the type specification (: Int?
), possibleInt
would be inferred to be of the Int
type instead of an Int
optional.
It is pretty verbose to say that a variable lacks a value. Instead, if an optional lacks a variable, we say that it is nil. So, both possibleString
and possibleArray
are nil, while possibleInt
is 10...