Optional binding and defer statements in iOS swift

In my previous article about swift optionals, I mentioned about optional binding.

5 min readJul 12, 2017

— Optional Binding (if -let statements) :

Use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.

An optional binding for the if statement is as follows −

if let constantName = someOptional {
//statements using 'constantName'
} else {
// the value of someOptional is not set (or nil).

Optional binding is the recommended way of unwrapping optionals.This method is safer than force unwrapping and implicit unwrapping. Refer this article for more info on this concept.

— if -var statements :

If you use the let then you will not be able to change myValue.

if let myValue = myObject.value as NSString? {
myValue = "Something else" // <-- Compiler error

On the other hand with var you can.

let someOptionalString:String?someOptionalString = "abcd"if var varString = someOptionalString {print(varString) //prints abcdvarString = "efgh"print(varString) //prints efgh