用不存在的 rawValue 初始化的枚举不会失败并返回 nil

Geo*_*org 6 enums mapkit swift

我在操场(Xcode 9.0.1)中有以下代码:

import MapKit

enum Test: UInt {
    case first
    case second
    case third
}

let test = Test(rawValue: 4) as Any
print(test)           // nil

let type = MKMapType(rawValue: 999)
print(type == nil)    // false
print(type!.rawValue) // 999
Run Code Online (Sandbox Code Playgroud)

MKMapType 定义为

enum MKMapType : UInt
Run Code Online (Sandbox Code Playgroud)

由于 MKMapType 的最大值为 5,我希望枚举的初始值设定项失败并返回 nil。相反,它返回 999。我是否在这里错过了一些 ObjC/Swift 桥接,或者这可能是一个错误?

Geo*_*org 5

我向 Apple 提交了一个错误,这是我收到的回复:

“工程已根据以下信息确定此问题的行为符合预期:

因为 C 枚举可能会在未来版本中添加值,或者甚至具有框架使用的“私有案例”值,这些值未包含在标头中,所以无法检查 Swift 中提供的值是否实际有效或无效。因此,init(rawValue:)必须像 C 类型转换一样产生一个值。Swift 开源项目中有关于如何在 Swift 的更高版本中改善这种情况的讨论,但 MKMapType 的初始化程序仍然不会返回 nil。”

感谢 Apple Engineering 的解释。