gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:40:53 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com