Swift switch语句考虑了Int的所有情况,但编译器仍然显示错误

Swift switch语句考虑了Int的所有情况,但编译器仍然显示错误,第1张

概述我理解 Swift中的switch语句必须是详尽的,否则我们必须提供一个默认的情况.我在网上看到了下面的代码,switch语句已经涵盖了Int中的所有情况,但是编译器仍然显示错误消息,交换机必须是详尽的,考虑添加一个default子句.有什么我想念的吗? extension Int { enum Kind { case Negative, Zero, Positive 我理解 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编译器没有
正确地确定switch语句的详尽性,例如
作为https://bugs.swift.org/browse/SR-766,Apple工程师Joe Groff
评论说:

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.

旧答案:编译器不太聪明,无法识别您已覆盖
所有可能的情况.一种可能的解决方案是添加默认值
具有fatalError()的情况:

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    }}

但是,这会编译,但会在运行时中止,因为您不能
创建范围1 … Int.max.更多关于此的信息
问题可以在文章Ranges and Intervals in Swift中找到.)

总结

以上是内存溢出为你收集整理的Swift switch语句考虑了Int的所有情况,但编译器仍然显示错误全部内容,希望文章能够帮你解决Swift switch语句考虑了Int的所有情况,但编译器仍然显示错误所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1037549.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存