2

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!

angli1937
  • 53
  • 4

1 Answers1

3

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

raidfive
  • 6,603
  • 1
  • 35
  • 32
Faiz Fareed
  • 1,498
  • 1
  • 14
  • 31
  • Thanks for the answer. Yes, the above NS_TYPED_ENUM will be converted as the following struct but my point is that the init(rawValue: RawValue) was very weird since the protocol https://developer.apple.com/documentation/swift/rawrepresentable define the init as fallible. Not sure why it becomes non-failible in this case... – angli1937 Apr 04 '19 at 18:40
  • Since your `NS_TYPED_ENUM` is converted as above mentioned struct, which proves your initial question is answered. and so for about `init(rawValue: RawValue)` its init is bailable or non-bailable you can ask it in another question. as i said earlier your initial question has been answered, so will you proceed my answer as correct answer while marking tick marking it. After that make another question as i said, so that we could reply that accordingly. Thanks – Faiz Fareed Apr 06 '19 at 09:13