extension Int { enum Kind { case Negative,Zero,Positive } var kind: Kind { switch self { case 0: return .Zero case let x where x > 0: return .Positive case let x where x < 0: return .Negative } } }
可以定义一个范围,如1 … Int.max,包括
最大可能的整数(比较 Ranges in Swift 3).所以这编译并按预期工作,
但仍需要一个默认大小写来满足编译器:
extension Int { enum Kind { case negative,zero,positive } var kind: Kind { switch self { case 0: return .zero case 1...Int.max: return .positive case Int.min...(-1): return .negative default: fatalError("Oops,this should not happen") } } }
还有其他错误报告,Swift编译器没有
正确地确定switch语句的详尽性,例如
作为https://bugs.swift.org/browse/SR-766,Apple工程师Joe Groff
评论说:@H_301_16@
Unfortunately,integer operations like ‘…’ and ‘<‘ are just plain functions to Swift,so it’d be difficult to do this kind of analysis. Even with special case understanding of integer intervals,I think there are still cases in the full generality of pattern matching for which exhaustiveness matching would be undecidable. We may eventually be able to handle some cases,but there will always be special cases involved in doing so.@H_301_16@
旧答案:编译器不太聪明,无法识别您已覆盖
所有可能的情况.一种可能的解决方案是添加默认值
具有fatalError()的情况:@H_301_16@
var kind: Kind { switch self { case 0: return .Zero case let x where x > 0: return .Positive case let x where x < 0: return .Negative default: fatalError("Oops,this should not happen") } }
或者使案例0:默认情况:@H_301_16@
var kind: Kind { switch self { case let x where x > 0: return .Positive case let x where x < 0: return .Negative default: return .Zero } }
(注:我最初认为以下内容可以正常工作
不需要默认情况:@H_301_16@
var kind: Kind { switch self { case 0: return .Zero case 1 ... Int.max: return .Positive case Int.min ... -1: return .Negative } }
但是,这会编译,但会在运行时中止,因为您不能
创建范围1 … Int.max.更多关于此的信息
问题可以在文章Ranges and Intervals in Swift中找到.)@H_301_16@