【问题标题】:Objective-C enums conform to RawRepresentableObjective-C 枚举符合 RawRepresentable
【发布时间】:2020-03-27 02:08:29
【问题描述】:
对此我有任何经验,例如以下用 objc 编写的枚举
typedef enum {
Type1,
Type2
} Type;
extension Type: RawRepresentable {
typealias RawValue = UInt32
}
当我尝试遵循 RawRepresentable 时编译器崩溃。我唯一可以想象的是 RawRepresentable 仅适用于 swift 枚举。
有什么想法吗?
【问题讨论】:
标签:
swift
rawrepresentable
【解决方案1】:
忘记使用原始 C 枚举并使用 Objective-C NS_ENUM 宏:
typedef NS_ENUM(NSInteger, MyEnumType) {
Type1,
Type2
};
然后在 Swift 中,枚举将已经是 RawRepresentable。您不能以这种方式添加该一致性。好吧,您可能可以,但您还必须声明 init?(rawValue:) 和 var rawValue。