我注意到奇怪的快速行为,因为在我看来,颜色变量不应该在下面写的开关的情况下强制解包,但是没有展开编译器会向我显示错误消息.
enum Colours: Int {
case Red = 0, White, Black
}
var colours: Colours!
colours = .Red
switch colours! { // <-- why I have to unwrap colours? As you can see colours are declared as '!'
case .Red: break
default: break
}
Run Code Online (Sandbox Code Playgroud)
如果colors变量未解包编译器显示错误:

在我看来,它是迅速的不一致,有没有人有一些想法?
Mar*_*n R 35
在switch语句中使用时,即使是隐式解包的选项也不会自动解包.(原因可能是你无法将它们与nil其他方面相匹配.)
所以你必须打开(强行使用
colours!哪个会崩溃colours == nil,或者使用可选绑定),或者 - 或者 - 匹配.Red?
哪个是以下的快捷方式.Some(.Red):
var colours: Colours!
switch colours {
case .red:
break // colours is .red
default:
break // colours is .white, .black or nil
}
Run Code Online (Sandbox Code Playgroud)
对于其他模式匹配表达式也是如此,例如
var colours: Colours!
switch colours {
case .Red?:
break // colours is .Red
default:
break // colours is .White, .Black or nil
}
Run Code Online (Sandbox Code Playgroud)
这也与枚举类型无关,只与模式中隐式解包的选项有关:
if case .Red? = colours {
// colours is .Red
} else {
// colours is .White, .Black or nil
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3928 次 |
| 最近记录: |