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
的所有 case 值吗?但我仍然收到错误?为什么我会收到此错误,我错过了什么吗?
最佳答案
Swift 仅在使用 enum
类型时真正验证 switch
block 是否详尽。即使打开 Bool
,除了 true
和 false
之外,还需要一个 default
block :
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/54859194/