问题描述
Swift编程指南说:您还可以使用带有可选绑定的隐式解包后的可选内容,以在单个语句中检查和解开它的值".当值已经解包时,为什么需要使用可选绑定?选项绑定会再次将其解包吗?
Swift Programming Guide says "You can also use an implicitly unwrapped optional with optional binding, to check and unwrap its value in a single statement". Why do you need to use optional binding when the value is already unwrapped? Does option binding unwrap it again?
推荐答案
调用隐式解包与使用!调用常规可选对象相同!之后.它仍然可以保留nil值,当它为nil时调用它会导致运行时错误,因此,如果不确定是否为nil,可以使用if let可选绑定.
Calling an implicitly unwrapped is the same as calling a regular optional with ! after it. It can still hold a nil value and calling it when it's nil will result in a runtime error, so you use the if let optional binding if you aren't sure if it is nil or not.
var myOptional: Int! = nil
10 + myOptional //runtime error
if let myUnwrapped = myOptional{
10 + myOptional //safe
}
这篇关于隐式展开时的可选绑定可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!