Purpose of forced unwrapping

一世执手 提交于 2019-12-04 07:42:39

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.

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