Optionals
Optionals may seem a little complicated at first glance, but actually they are fairly simple. This page is intended to help you decide if you should use an optional, and if so, in what way
When declaring variables
-
You know the value for the variable at the point it is declared or the class is initialised, and that variable will always have a value
- Do not use an optional
//set value at declaration
var myString = "abc"
//alternatively set value on class initialisation (using designated initialiser)
var someString : String
init(){
someString = "abc"
}
-
You do not have a value for the variable when you declare it, but you can guarantee that whenever you access it, it will have a value
-
Declare the variable as an implicitly unwrapped optional and use it as normal
var myString : String!
-
Regardless of whether or not you know the value of a variable when you declare it, you know at some point when you access it, it may not have a value
-
Declare it as an optional
var myString : String?
When using optionals
- At the point of use, you know the optional will have a value
-
Force Unwrap it
var actualString = myString!
- At point of use the optional may not have a value
-
Check it is not nil first, e.g.:
if let actualString = myString{
//do something with actualString
}