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
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