1

I am writing an OS X/iOS framework in Objective-C, and I would like for the framework to be useful for developers using either Objective-C or Swift.

In normal Objective-C enums are defined like this (this example is taken directly from Apple's own UIView class reference).

typedef enum {
   UIViewAnimationCurveEaseInOut,
   UIViewAnimationCurveEaseIn,
   UIViewAnimationCurveEaseOut,
   UIViewAnimationCurveLinear
} UIViewAnimationCurve;

To make this enum Swift-friendly, my understanding is that it should be declared like this.

typedef NS_ENUM(NSInteger, UIViewAnimationCurve) {
    UIViewAnimationCurve_EaseInOut,
    UIViewAnimationCurve_EaseIn,
    UIViewAnimationCurve_EaseOut,
    UIViewAnimationCurve_Linear
};

This allows the enum to be accessed in the style of let curve: UIViewAnimationCurve = .EaseInOut from Swift.

My problem is that the NS_ENUM and underscore method produces strangely named enums when used from Objective-C. The NS_ENUM method allows dot notation to be used from Swift, but it also means that any ObjC code will need to use an underscore in the enumerated name, which is undesirable.

How can I allow dot notation for Swift while still preserving Objective-C style naming conventions for within ObjC code?

William Rosenbloom
  • 2,152
  • 11
  • 29

2 Answers2

3

You simply follow the usual convention – no underscoring is necessary. Swift compiler is smart enough to just cut the common prefix out (the part that matches the enum type name). You do have to use an NS_ENUM for the enum to be made visible to Swift, but it's good practice anyway.

Case in point, for instance UIViewAnimationCurve is defined in an Objective-C header in just the form you describe in your first code example and works just fine in Swift:

enter image description here

mz2
  • 4,402
  • 1
  • 23
  • 44
0

If you define it like this:

typedef long TrafficLightColor NS_TYPED_ENUM;

TrafficLightColor const TrafficLightColorRed;
TrafficLightColor const TrafficLightColorYellow;
TrafficLightColor const TrafficLightColorGreen;

if get compiled to swift like this:

struct TrafficLightColor: RawRepresentable, Equatable, Hashable {
    typealias RawValue = Int

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

    static var red: TrafficLightColor { get }
    static var yellow: TrafficLightColor { get }
    static var green: TrafficLightColor { get }
}

Looks like what you need, anyway take a look at: https://itunes.apple.com/us/book/using-swift-with-cocoa-and-objective-c-swift-4-1-beta/id1002624212?mt=11

Boris
  • 159
  • 1
  • 6