Swift switch语句考虑了Int的所有情况,但编译器仍然显示错误
我理解
Swift中的switch语句必须是详尽的,否则我们必须提供一个默认的情况.我在网上看到了下面的代码,switch语句已经涵盖了Int中的所有情况,但是编译器仍然显示错误消息,交换机必须是详尽的,考虑添加一个default子句.有什么我想念的吗?
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 } } }
更新Swift 3:Swift 3引入了ClosedRange
可以定义一个范围,如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编译器没有
旧答案:编译器不太聪明,无法识别您已覆盖 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:默认情况: var kind: Kind { switch self { case let x where x > 0: return .Positive case let x where x < 0: return .Negative default: return .Zero } } (注:我最初认为以下内容可以正常工作 var kind: Kind { switch self { case 0: return .Zero case 1 ... Int.max: return .Positive case Int.min ... -1: return .Negative } } 但是,这会编译,但会在运行时中止,因为您不能 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- 浅析Flex代码格式化功能
- 使用SQLite方式存储数据
- oracle字段追加
- react0.45.0版本问题 An error was encountered processing
- postgresql – 嵌入了postgres jsonb列的GIN索引吗?
- vue的无缝滚动组件vue-seamless-scroll实例
- c# – 具有多个NIC的UDP多播仅在一个接口处于活动状态时有效
- Flash4.5 + eclipse3.6安装
- c – 如何使用boost :: log :: BOOST_TRIVIAL_LOG更改默认格
- flash builder4里面关于StyleManager和IStyleManager2