Optionals in Swift


var a : Int            // create a swift variable of type int
var b = a + 10      //compiler will thrown an error because a is not initialized

Alternative to above

When your using ‘?”/optional , that means your explicitly telling the compiler that a may or may not have the value.

var a : Int?
var b = a! + 5     // the compiler suggest to unwrap the optional, this is called force unwrapping and program will crash if in case a does not have value so force unwrapping of optionals is always dangerous and should not do it unless your sure about var holding a value.

then what is the safe way to deal with optionals? answer is optional binding 

if let nonOptionalValue = a {
var b = nonOptionalValue + 5  // if a is nil, this statement is not executed and force unwrapping is not required in this case because we knew that a is not nil and has a value for sure.

}

No comments:

Post a Comment