Why use optionals?

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 = nil

The great thing about Swift is that it will not let you pass an optional value, which may or may not be nil, to a function that is expecting a non-nil value. This is a massive safety boost; no longer will there be crashes by your program attempting to access a value that does not exist. Or at least, Swift makes you work harder to make these crashes possible. If a function is not equipped to deal with a nil value, set its argument type to non-optional.

Be sure to be clear about the fact that an Int and an Int? are not the same type. An attempt to assign an optional value to a non-optional type will produce a type error, so trying this:

let x: Int = squareOfTwo 

Will result in Xcode showing you a warning like this: