Variables

Optionals in Swift

In Swift, variables must have a value. Optionals are used to assign a value of nil to a variable, if no value is provided. Optional variables cannot have their values accessed directly. They need to be 'unwrapped' in order for the value to be used.


Syntax
var optionalVariable: dataType?
//this also works
var optionalVariable2: Optional<dataType>
//accessing optional value
let optionalValue = optionalVariable!

Notes

The default value for an optional variable is nil (if no value is provided). The value for an optional can be provided, but set to nil later.

Regular (non-optional) variables cannot be set to nil.

Optionals are often used when the casting one type to another, and the format is not guaranteed to be valid. Statements that evaluate to optional types can be used in conditional statements.


Example
var gradeString: String = "85"
//converting to int, assigns nil if it is of invalid format
var grade: Int? = Int(gradeString)

if grade != nil {
    print("The student's grade is: \(grade)")
}

< Constants   |   Arrays >

© 2019 SyntaxDB. All Rights Reserved.