Search code examples
swiftrawrepresentable

Objective-C enums conform to RawRepresentable


Any exprerience on this I have for example the following enum written in objc

typedef enum {
  Type1,
  Type2
} Type;

extension Type: RawRepresentable {
    typealias RawValue = UInt32
}

compiler crashes when I'm trying to conform to RawRepresentable.The only thing that I can imaging is that RawRepresentable works only with swift enums.

Any ideas?


Solution

  • Forget about using raw C enum and use the Objective-C NS_ENUM macro:

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

    Then in Swift the enum will be already RawRepresentable. You cannot add that conformance this way. Well, you probably could, but you will have to also declare init?(rawValue:) and var rawValue.