swift - 强制解包的目的

标签 swift forced-unwrapping

在 swift 文档中,你可以找到这个:

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

有了这个解释

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:

好的,知道了,但是它有什么用呢?如果我没有像这样强制展开,那就不一样了:

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

谢谢你启发我:)

最佳答案

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

没有。 Optional 是一种不同的类型。如果您实际运行上面的代码而不展开(这在 Playground 上是微不足道的),您可以立即看到差异。

可选打印为 Optional(123),未包装打印为 123。如果不首先展开它,就不能将可选的传递给需要特定类型的东西。

了解 Optional 是完全不同的类型,而不是特定类型的特殊类型(例如,没有“可选 Int”,有一个包含 Int 的 Optional)是理解这一点的关键。我写过它here如果您对更长的解释感兴趣。

关于swift - 强制解包的目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25324774/

相关文章:

ios - 如何在swift中将标签的文本保存为整数变量?

Swift View Controller 声明返回 nil

ios - 带有自定义 init 的 UIView 不起作用

ios - 不在 guard 语句中使用展开

ios - 触发 segue 时出现错误 "fatal error: unexpectedly found nil while unwrapping an Optional value"

ios - 可选类型的默认值 'URL?'

ios - 如何检查我的应用程序是否启用了 Face id?

ios - 在 Swift 中实现 UIImagePickerController

xcode - 选择 Xcode 6 Beta 时 UITabBarItem 图像消失

Swift:将凭据与 Firebase 和用户名的附加文本字段一起使用