Swift is, above all, a language for writing safe code, and its method of dealing with values that may or may not be nil
is arguably its most important feature.
Let's look at two lines of code:
var squareOfTwo = Int("4") var squareOfThree = Int("Yellow")
The Int
initializer can take a String
as its argument, and will return a valid Int
if it can. If it cannot, it will return nil
. The return value of that initializer is an optional Int
. Thus, the two variables declared above evaluate as follows:
squareOfTwo // 4 squareOfThree // nil
In Swift, an optional is a special type that holds either a value or nil
, and is marked by a question mark appended to the type of value it will hold:
var optVal1: Int?
We can also initialize an optional directly with a literal:
var optVal2: Int? = 2
It is important to note that nil
is not the same as zero: 0
is a valid integer, nil
is no value at all. So, the following two lines of code do not produce the same result:
optVal1 = 0 optVal1...