苹果 documentation说
Every switch statement must be exhaustive. That is, every possible value of the type being considered must be matched by one of the switch cases.
所以在新的 Xcode 中我放置了这样的代码
println(UInt16.min); // Output : '0'
println(UInt16.max); // Output : '65535'
var quantity : UInt16 = 10;
switch quantity {
case 0...65535: //OR case UInt16.min...UInt16.max:
println();
default:
println();
}
现在,如果我删除默认部分,我会得到一个编译器错误:
Switch must be exhaustive
Do you want to add missing cases? Fix
所以我的问题是关于我提到的一个案例 case 0...65535:
我没有提到 UInt16
的所有案例值吗?但我仍然收到错误消息??为什么我会收到此错误,我错过了什么吗??
最佳答案
Swift 仅在使用 enum
类型时真正验证 switch
block 是否详尽无遗。即使打开 Bool
也需要一个 default
除了 true
和 false
之外:
var b = true
switch b {
case true: println("true")
case false: println("false")
}
// error: switch must be exhaustive, consider adding a default clause
然而,对于 enum
,编译器很乐意只查看这两种情况:
enum MyBool {
case True
case False
}
var b = MyBool.True
switch b {
case .True: println("true")
case .False: println("false")
}
如果为了编译器的缘故,你需要包含一个 default
block ,但又没有任何事情要做,break
关键字就派上用场了:
var b = true
switch b {
case true: println("true")
case false: println("false")
default: break
}
关于ios - Swift 中开关盒的穷举条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552433/