Swift Optional is used at that place where variable can be nil. To set a variable as Optional, question mark is added to the type. For example,
var optionalExample : Int?
Now by default optionalExample variable will have nil means no value.
optionalExample = 5
Now optionalExample variable has a value 5.
You can assign nil to optional variable at any time using assignment operator. For example,
optionalExample = nil
If there is possibility that value can nil then variable is automatically set to optional type. For example, initializing a variable with type conversion from String to Int. So there is possibility that there comes a String value that could not be converted to an integer. For example,
let myValue = "123" var myNumber = Int(myValue)
So now myNumber is declared as Int? (optional Int) and it has currently value 123.
Forced Unwrapping
If you are sure that an optional definitely has a value then you can force unwrap it to use that value using exclamation mark after that constant or variable. For example,
let defNumber : Int? = 345 if(defNumber != nil) { print(“Value : \(defNumber!)”) }
Note that "\( )" has been used to write a number in the String. It has nothing to do with Forced Unwrapping.
Optional Binding
Optional Binding is to find out that either optional has a value or not. If the optional has value only then if’s block of statements in curly brackets will be executed.
if let myNumber = myOptional { // Set of statement to be executed if myOptional is not nil. }
Not that if myOptional is not nil then its value would be assigned to a temporary constant myNumber.