Purpose of forced unwrapping
Asked Answered
B

2

5

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 :)

Byelection answered 15/8, 2014 at 10:16 Comment(0)
G
15

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.

Gigolo answered 15/8, 2014 at 10:24 Comment(1)
Nice article you wrote, very clear to understand, great work thank you ! Swift makes me hallucinate, it's awesome in each tiny feature :oByelection
K
2

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).")
}
Knorr answered 15/8, 2014 at 10:43 Comment(1)
You don't need the ! in that code, since you've done optional bindingGigolo

© 2022 - 2024 — McMap. All rights reserved.