问题
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 :)
回答1:
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.
回答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).")
}
来源:https://stackoverflow.com/questions/25324774/purpose-of-forced-unwrapping