Objc visible string enum but not RawRepresentable

2k Views Asked by At

I want to use enum that is visible both in objective C and Swift but not conform to protocol RawRepresentable.

  1. I tried to have an enum of string both visible in Objc and Swift thus I use

    typedef NSString *myEnum NS_TYPED_ENUM;

  2. I tried to take advantage of the myEnum(rawValue: ) -> myEnum? function but I found the enumType has automatically conform to

    public struct myEnum : Hashable, Equatable, RawRepresentable { public init(rawValue: String) }

My question is how to create enum that is visiable in Objc and Swift but not conform to this protocol? Thanks for all the help!

1

There are 1 best solutions below

2
On BEST ANSWER

Swift Language Enhancements

... Swift enums can now be exported to Objective-C using the @objc attribute. @objc enums must declare an integer raw type, and cannot be generic or use associated values. Because Objective-C enums are not namespaced, enum cases are imported into Objective-C as the concatenation of the enum name and case name.

Above From Xcode 6.4 Release Notes


For this purpose you define the values in Objective-C, you can use the NS_TYPED_ENUM macro to import constants in Swift For example: .h file

typedef NSString *const ProgrammingLanguage NS_TYPED_ENUM;

FOUNDATION_EXPORT ProgrammingLanguage ProgrammingLanguageSwift;
FOUNDATION_EXPORT ProgrammingLanguage ProgrammingLanguageObjectiveC;

.m file

ProgrammingLanguage ProgrammingLanguageSwift = @"Swift";
ProgrammingLanguage ProgrammingLanguageObjectiveC = @"ObjectiveC";

In Swift, this is imported as a struct as such:

struct ProgrammingLanguage: RawRepresentable, Equatable, Hashable {
    typealias RawValue = String

    init(rawValue: RawValue)
    var rawValue: RawValue { get }

    static var swift: ProgrammingLanguage { get }
    static var objectiveC: ProgrammingLanguage { get }
}

Although the type is not bridged as an enum, it feels very similar to one when using it in Swift code.

You can read more about this technique in the "Interacting with C APIs" of the Using Swift with Cocoa and Objective-C documentation