在 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/