2
2
.
.
2
2
.
.
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
[
[
R
R
]
]
Optional is Constant or Variable that can be null 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 null
has Value you get that Value "John"
is not initialized you get variable 'age' must be initialized
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"
Syntax
//DECLARE OPTIONAL.
let name : String? = "John" //Optional Constant
var age : Int? = 20 //Optional Variable
var height : Int? = null //null
var weight : Int? //Not initialized. Throws error if referenced without asigning a value.
//REFERENCE OPTIONAL.
name = "Bill"
println(name) //Bill
println(height) //null