首页 > 解决方案 > Objective-C 枚举符合 RawRepresentable

问题描述

对此我有任何经验,例如以下用 objc 编写的枚举

typedef enum {
  Type1,
  Type2
} Type;

extension Type: RawRepresentable {
    typealias RawValue = UInt32
}

当我试图符合 RawRepresentable 时,编译器崩溃。我唯一可以想象的是 RawRepresentable 仅适用于 swift 枚举。

有任何想法吗?

标签: swiftrawrepresentable

解决方案


忘记使用原始 C 枚举并使用 Objective-CNS_ENUM宏:

typedef NS_ENUM(NSInteger, MyEnumType) {
    Type1,
    Type2
};

然后在 Swift 中,枚举已经是RawRepresentable. 您不能以这种方式添加该一致性。好吧,您可能可以,但您还必须声明init?(rawValue:)and var rawValue


推荐阅读