问题描述
Apple 说
所以在新的Xcode中我放置了这样的代码
So in new Xcode I have placed a code like this
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();
}
现在,如果我删除默认部分,我会收到编译错误,显示开关必须是详尽的
Now if i remove the default section I get a compile error showing that switch must be exhaustive
所以我的问题是我提到的一个案例案例0 ... 65535:
我没有提到 UInt16
的所有案例值?但我仍然得到一个错误?为什么我收到这个错误,我错过了什么?
So my question is for a case that I have mentioned as case 0...65535:
have I not mentioned all the case values for an UInt16
?? But still I am getting an error ?? Why am I getting this error, Did i miss something ??
推荐答案
Swift只能真正验证使用
块是详尽无遗的。即使开启枚举
类型时,切换 Bool
,除了 true $ c $之外,还需要
默认
块c>和 false
:
Swift only truly verifies that a switch
block is exhaustive when working with enum
types. Even a switching on Bool
requires a default
block in addition to true
and false
:
var b = true
switch b {
case true: println("true")
case false: println("false")
}
// error: switch must be exhaustive, consider adding a default clause
但是,使用枚举
,编译器很乐意只看两种情况:
With an enum
, however, the compiler is happy to only look at the two cases:
enum MyBool {
case True
case False
}
var b = MyBool.True
switch b {
case .True: println("true")
case .False: println("false")
}
如果你需要包含默认
阻止编译器的缘故,但没有任何操作, break
关键字派上用场:
If you need to include a default
block for the compiler's sake but don't have anything for it to do, the break
keyword comes in handy:
var b = true
switch b {
case true: println("true")
case false: println("false")
default: break
}
这篇关于Swift中开关盒的穷举条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!