0

I have a typedef definition in Objective-C like this:

typedef NS_ENUM(NSInteger, MyStatus) {
    MyStatusUnknown = -1,
    MyStatusBad = 0,
    MyStatusGood = 1
}

This enum is in a pod, and it's used by several downstream pods, and the app like this:

@property (readonly, nonatomic, assign) MyStatus myStatus;

I need to convert class with typedef to Swift without changing the signature of enum definition in downstream pods.

I tried a straight forward conversion first:

enum MyStatus: Int {
    case unknown = -1
    case bad
    case good
}

But in this case, the property statement above will show an error:

Interface type cannot be statically allocated

This error can be resolved by changing property to

@property (readonly, nonatomic, assign) MyStatus *myStatus;

but as I said before, I cannot change this property definition.

So how to convert typedef to Swift, while maintaining its backward compatibility with existing Objective-C property?

Cœur
  • 37,241
  • 25
  • 195
  • 267
timbre timbre
  • 12,648
  • 10
  • 46
  • 77
  • you forgot to add `case` keyword `case unknown = -1, bad, good` – Leo Dabus Jan 04 '20 at 23:58
  • @LeoDabus yes, thanks, that's a mistake in question though, not in real code (I simplified actual enum I converted to just show a minimum here – timbre timbre Jan 05 '20 at 01:07
  • Does this answer your question? [Is it possible to use Swift's Enum in Obj-C?](https://stackoverflow.com/questions/24139320/is-it-possible-to-use-swifts-enum-in-obj-c) – Willeke Jan 05 '20 at 08:53
  • @Willeke I didn't ask how to use Swift enum in Objective C, I *know* how to do that. I asked **how to preserve statically allocated property after converting Objective C typedef to Swift enum** - entirely different question. – timbre timbre Jan 05 '20 at 19:37

1 Answers1

0

In your *.swift file you have to declare (@objc is required)

@objc
public enum MyStatus: Int {
    case unknown = -1
    case bad
    case good
}

Then autogenerated -Swift.h will contain

typedef SWIFT_ENUM(NSInteger, MyStatus, closed) {
  MyStatusUnknown = -1,
  MyStatusBad = 0,
  MyStatusGood = 1,
};

including that -Swift.h in precompiled headers (or directly if needed) will give that declaration available for Objective-C file having myStatus property.

Asperi
  • 228,894
  • 20
  • 464
  • 690