Search Your Question

What is better, Force unwrapping or optional binding?

Ans :

Force unwrapping :  It's the action of extracting the value contained inside an Optional. This operation is dangerous because you are telling the compiler: I am sure this Optional value does contain a real value, extract it!

let anOptionalInt: Int? = 1
let anInt: Int = anOptionalInt!

But here if, anOptionalInt has nil value, then fatal error will be generated. Unexpectedly found nil while unwrapping an Optional value.

Optional Binding: Using if let, we can store value in one variable if value is not nil. By this way, fatal error never be generated. This way will be used when we are not sure that variable has value or nil. This method is better because no chances of crashing app.

if let tempStockCode = stockCode {
    let message = text + tempStockCode
    println(message)
}

Implicitly unwrapped optionals : 

let anOptionalInt: Int! = 1
let anInt: Int = anOptionalInt

anOptionalInt is never be optional. But it can has value of nil.

No comments:

Post a Comment

Thanks