ali*_*ego 5 switch-statement ios swift xcode10 swift4.2
我有以下枚举:
enum ExampleEnum {
case one
case two
case three
case four
}
Run Code Online (Sandbox Code Playgroud)
以及以下属性定义:
var exampleProperty: ExampleEnum!
Run Code Online (Sandbox Code Playgroud)
在Swift 4.2之前,我使用以下switch语句:
switch self.exampleProperty {
case .one:
print("case one")
case .two:
print("case two")
case .three:
print("case three")
case .four:
print("case four")
default:
break
}
Run Code Online (Sandbox Code Playgroud)
自从切换到Swift 4.2之后,这个switch语句给了我错误:
Enum case 'one' not found in type 'ExampleEnum?'
Run Code Online (Sandbox Code Playgroud)
我觉得这很奇怪,因为我已经用感叹号清楚地定义了类型,以隐式解开可选内容。但是,似乎没有这样做。为了使错误消失,我需要执行以下切换:
switch self.exampleProperty! {
case .one:
print("case one")
case .two:
print("case two")
case .three:
print("case three")
case .four:
print("case four")
}
Run Code Online (Sandbox Code Playgroud)
我在上面所做的是再次解包了exampleProperty变量,即使定义是隐式解包的,也从开关中删除了默认值。
只是想知道为什么在4.2快速更改?是switch语句中的更改,还是为什么再次需要这种解包。看来多余吗?
对我来说它有效
if let myEnumCase = self.exampleProperty {
switch myEnumCase {
case .one:
print("case one")
case .two:
print("case two")
case .three:
print("case three")
case .four:
print("case four")
}
}
Run Code Online (Sandbox Code Playgroud)
但我仍然很困惑,如果我们用强力包裹那么为什么我们需要这个
任何建议将不胜感激
| 归档时间: |
|
| 查看次数: |
732 次 |
| 最近记录: |