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编译器没有
正确地确定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中找到.)

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...