【发布时间】:2015-01-12 12:36:46
【问题描述】:
在 Swift 中,我如何在 switch 语句中编写一个 case 来测试被切换的值与 optional 的内容,如果 optional 包含 nil 则跳过 case? p>
这是我想象中的样子:
let someValue = 5
let someOptional: Int? = nil
switch someValue {
case someOptional:
// someOptional is non-nil, and someValue equals the unwrapped contents of someOptional
default:
// either, someOptional is nil, or someOptional is non-nil but someValue does not equal the unwrapped contents of someOptional
}
如果我只是这样写,编译器会抱怨someOptional 没有解包,但是如果我通过在末尾添加! 来明确解包,我当然会随时出现运行时错误someOptional包含nil。添加? 而不是! 对我来说是有意义的(本着可选链接的精神,我想),但不会使编译器错误消失(即实际上并没有解开可选)。
【问题讨论】:
标签: swift enums switch-statement optional