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

标签 swift enums mapkit

我在 playground (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

MKMapType 定义为

enum MKMapType : UInt

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

最佳答案

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

"Engineering has determined that this issue behaves as intended based on the following information:

Because C enums may have values added in future releases, or even have "private case" values used by the framework that are not included in the headers, there's no way to check whether a value provided in Swift is actually valid or invalid. Therefore, init(rawValue:) is obliged to produce a value just as a C cast would. There are discussions in the Swift Open Source project on how to improve this situation in later versions of Swift, but the initializer for MKMapType still won't return nil."

感谢 Apple Engineering 的解释。

关于swift - 使用不存在的 rawValue 初始化的枚举不会失败并返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47034190/

相关文章:

ios - UIView 扩展中的 UIButton

ios - 重新定位合法标签 ( MKAttributionLabel )

iPhone - MapKit - 搜索位置和移动注释

algorithm - 在 mapKit 中获取凹包

c++ - 虚函数返回的枚举协方差

Swift 子类的 init 必须在调用 super 之前设置所有属性,但是属性需要 super 的 init 先完成

Swift LayoutSubViews 顺序

xcode - 从函数 Xcode/Swift 更改 label.text

fluent-nhibernate - 使用 Fluent Nhibernate 映射自定义枚举类

java - 为什么我可以匿名子类化枚举而不是最终类?