加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:33:43 所属栏目:百科 来源:网络整理
导读:我理解 Swift中的switch语句必须是详尽的,否则我们必须提供一个默认的情况.我在网上看到了下面的代码,switch语句已经涵盖了Int中的所有情况,但是编译器仍然显示错误消息,交换机必须是详尽的,考虑添加一个default子句.有什么我想念的吗? extension Int { enu
我理解 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中找到.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读