ios - Swift 中开关盒的穷举条件

标签 ios swift

苹果 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 除了 truefalse 之外:

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/

相关文章:

ios - Xcode 7 Swift 2 无法实例化通用 UITableViewController 的 UIViewController 子类

ios - 使 UILabel 很好地适合 Collection View Cell

ios - 如何使用 AVPlayer addperiodictimeobserverforinterval 函数更新 uilabel?

ios - 如何在 UINavigationBar 下方添加 UISegmentControl?

iOS FCM 推送通知无法快速在后台状态下工作?

swift - 从字典 Swift 2 随机生成属性

javascript - 如何阻止 iPhone 在上传到后端时重新压缩图像?

ios - 检查对象是否存在于 NSDictionary 的 NSMutableArray 中

android - iOS如何获取图像的像素值

iphone - 我应该在发布我的应用程序时删除 NSLogs