Introducing optionals
When we declare variables in Swift, they are by default non-optional, which means that they must contain a valid, non-nil value. If we try to set a non-optional variable to nil, it will result in a Nil cannot be assigned to type '{type}'
error, where {type}
is the type of the variable.
For example, the following code will throw an error when we attempt to set the message
variable to nil
because message
is a non-optional type:
var message: String = "My String" message = nil
It is very important to understand that nil in Swift is very different from nil in Objective-C or other C-based languages. In these languages, nil is a pointer to a non-existent object; however, in Swift nil is the absence of a value. This concept is very important to fully understand optionals in Swift.
A variable defined as an optional can contain a valid value or it can indicate the absence of a value. We indicate an absence of a value by assigning it a special nil value. Optionals of...