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

时间:2017-10-31 11:23:45

标签: swift enums mapkit

我在操场上有以下代码(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桥接或者这可能是一个错误吗?

1 个答案:

答案 0 :(得分:2)

I filed a bug with Apple and this is the reply I received:

"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."

Thanks to Apple Engineering for this explanation.