2
2
.
.
3
3
.
.
3
3
O
O
p
p
t
t
i
i
o
o
n
n
a
a
l
l
s
s
I
I
n
n
f
f
o
o
Optional is Constant or Variable that can be nil to indicate absence of value (hence the name since value is optional).
This is symbolized by appending question mark '?' to Data Type: String?, Int?.
Question mark '?' symbolizes that we are wondering if Optional contains Value of specified Data Type or if it is empty.
If Optional is of type String?, and we set it to null, it means that Optional is empty (it has no String value stored in it).
When you reference Optional which
is null you get nil
has Value you get Optional("John") (to get actual Value, in this case a String, you need to Unwrap Optional)
is not initialized you get variable 'age' used before being initialized
Optional Unwrapping is checking the value of the Optional and then getting its value if it is not nil.
Optional Chaining is checking the value of the Optional and then calling property or method on it if it is not nil.
Content
Optional Syntax
Unwrap Optional
Optional Chaining
O
O
p
p
t
t
i
i
o
o
n
n
a
a
l
l
S
S
y
y
n
n
t
t
a
a
x
x
Optional is declared by
using required Keyword let or var let or var (to declare Constant or Variable)
followed by required Name name
followed by required Data Type String
followed by required question mark ? ?
followed by optional Value "John"
Optional Syntax
//DECLARE OPTIONAL.
let name : String? = "John" //Optional Constant
var age : Int? = 20 //Optional Variable
var height : Int? = nil //nil
var weight : Int? //Not initialized. Throws error if referenced without asigning a value.
//REFERENCE OPTIONAL.
name = "Bill"
print(name) //Optional("Bill")
print(name!) //Bill is Forced Unwrapped
print(height) //nil
U
U
n
n
w
w
r
r
a
a
p
p
O
O
p
p
t
t
i
i
o
o
n
n
a
a
l
l
This example shows how to unwrap Optional using "if" statement (also known as Optional Binding).
"if" statement checks if one or more Optionals contain a value
if they all do, values are copied into temporary constants or variables and body of if statement is executed
if at least one doesn't, if statement is skipped (code continues as usual with next statement usually else or else if)
Unwrap Optional
//DECLARE OPTIONALS.
var name : String? = "John"
var age : Int? = 20
//UNWRAP OPTIONALS.
if let unwrapedName = name, var age = age {
print("\(unwrapedName) is \(age) years old")
}
O
O
p
p
t
t
i
i
o
o
n
n
a
a
l
l
C
C
h
h
a
a
i
i
n
n
i
i
n
n
g
g
Optional Chaining appends '?' after referencing Optional
first to check if Optional Value is nil
and then to calling Property or Method on the Optional if value is not nil (in order to avoid null pointer Exception)
Since the result of Optional Chaining is also an Optional we need to unwrap it to get the Value as shown by the example.
Optional Chaining
if let room = building?.getFloor(8)?.getFlat(10)?.getRoom("bathroom")? {
print(room )
}