gpt4 book ai didi

objective-c - 使用 NS_ENUM 的 rawValue 初始值设定项定义的枚举不会失败

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

我有一个 Objective-C 文件,其中的枚举定义如下:

typedef NS_ENUM(NSInteger, State) {
State_ACTIVE = 0,
State_PENDING = 1,
State_CANCELED = 2
};

在我的 swift 代码中,如果我执行 let state = State(rawValue: 100),通常这应该返回 nil,因为它是一个可失败的初始化程序。然而,当枚举被这样声明时(使用 NS_ENUM),初始化成功,并且没有迹象表明这是一个无效的枚举值。这是 Xcode 中的错误,还是按预期工作?

最佳答案

这是预期的行为。对于桥接到 Swift 的任何 NS_ENUM,构造函数永远不会返回 nil

尝试将它与 iOS SDK 中桥接到 Swift 的一些其他枚举一起使用,这些枚举具有意外的值。它们都将返回非零值,即使对于未由枚举定义的 rawValue 也是如此:

UITableViewCellStyle(rawValue: 7) // "Optional(__C.UITableViewCellStyle)"
UITableViewCellAccessoryType(rawValue: 9999) // "Optional(__C.UITableViewCellAccessoryType)"

或者,使用 unsafeBitCast:

unsafeBitCast(42, UITableViewCellEditingStyle.self) // "Optional(__C.UITableViewCellStyle)"

Martin R 指出,这记录在Xcode 6.3 release notes :

Imported NS_ENUM types with undocumented values, such as UIViewAnimationCurve, can now be converted from their raw integer values using the init(rawValue:) initializer without being reset to nil. Code that used unsafeBitCast as a workaround for this issue can be written to use the raw value initializer. For example:

let animationCurve =  
unsafeBitCast(userInfo[UIKeyboardAnimationCurveUserInfoKey].integerValue,
UIViewAnimationCurve.self)

can now be written instead as:

let animationCurve = UIViewAnimationCurve(rawValue:  
userInfo[UIKeyboardAnimationCurveUserInfoKey].integerValue)!

关于objective-c - 使用 NS_ENUM 的 rawValue 初始值设定项定义的枚举不会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35758237/

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