Purpose of forced unwrapping

走远了吗. 提交于 2019-12-21 17:19:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!