Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of forced unwrapping

In swift documentation, you can find this :

if convertedNumber != nil {
    println("convertedNumber has an integer value of \(convertedNumber!).")
}
// prints "convertedNumber has an integer value of 123." 

With this explaination

Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value:

Ok, got it, but what's the usefulness of it ? Wouldn't be the same if I didn't forced the unwrapping like :

if convertedNumber != nil {
    println("convertedNumber has an integer value of \(convertedNumber).")
}
// prints "convertedNumber has an integer value of 123."

Thank for enlightening me :)

like image 879
Tancrede Chazallet Avatar asked Aug 15 '14 10:08

Tancrede Chazallet


2 Answers

Wouldn't be the same if I didn't forced the unwrapping

No. An Optional is a different type. If you actually run the code above without unwrapping (which is trivial in a playground) you can see the difference straight away.

The optional prints as Optional(123), the unwrapped prints as 123. You can't pass the optional to something that expects a specific type without unwrapping it first.

Understanding that Optionals are a different type altogether, rather than a specialised type of a specific type (e.g. there is no "optional Int", there is an Optional which contains an Int) is key to understanding this. I've written about it here if you're interested in a longer explanation.

like image 197
jrturton Avatar answered Oct 01 '22 17:10

jrturton


Alternatively, you can conditionally unwrap an optional

if let convertedNumber = <some optional> {
    // If the optional contains a value, then convertedNumber is now the unwrapped value.
    println("convertedNumber has an integer value of \(convertedNumber).")
}
like image 22
Anorak Avatar answered Oct 01 '22 18:10

Anorak