Swift - Data Type Optionals

Introduction

Swift makes a clear distinction between "no value" and all other values.

"No value" is referred to as nil and is a different type from all others.

To create a variable to have nil value, use optional variable.

You define optional variables by using a question mark (?) as part of their type:

// Optional integer, allowed to be nil 
var anOptionalInteger  : Int? = nil 
anOptionalInteger = 42 

Only optional variables can be set to nil.

If a variable isn't defined as optional, it's not allowed to be set to the nil value:

// Nonoptional (regular), NOT allowed to be nil 
var aNonOptionalInteger = 42 
//aNonOptionalInteger = nil 
// ERROR: only optional values can be nil 

If you create an optional variable and don't assign it a value it will default to nil.

You can check to see if an optional variable has a value by using an if statement:

if anOptionalInteger  != nil { 
    print("It has a value!") 
} 
else { 
    print("It has no value!") 
} 

Related Topics

Exercise