2

I have an enum like

typedef NS_ENUM(NSInteger, MyEnum) {
  MyEnumCase1,
  MyEnumCase2,
  ...
};

and a function that maps those enum values to arbitrary strings

FOUNDATION_EXPORT NSString *myEnumString(MyEnum val);

Is it possible to expose this to Swift as a property?

I've tried

FOUNDATION_EXPORT NSString *myEnumString(MyEnum val) NS_SWIFT_NAME(MyEnum.stringVal);

but the compiler gives me the warning "'swift_name' attribute argument must be a string literal specifying a Swift function name" and Swift callers don't see stringVal as a property on values of MyEnum.

and I've tried

FOUNDATION_EXPORT NSString *myEnumString(MyEnum val) NS_REFINED_FOR_SWIFT;

but my Swift extension

extension MyEnum {
  var stringVal {
    return __myEnumString(self)
  }
}

can't find __myEnumString().

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Greg
  • 10,360
  • 6
  • 44
  • 67
  • 1
    I don't know how to solve your issue, but as a workaround I would define a new `@interface SomeName` and just crate a wrapper of `myEnumString` inside that interface. Another option is to convert code over to swift (since making enum and its extension visible from swift to objc is easier) – timbre timbre Jan 05 '23 at 19:03
  • @Greg: Did you have a chance to check the answer? Please let me know if anything is unclear. – Martin R Jan 13 '23 at 09:30
  • I haven't had a chance to revisit this yet. I'll post when I do. – Greg Jan 18 '23 at 20:53

1 Answers1

4

The Swift function name passed to NS_SWIFT_NAME must include the implicit self: argument, and to import it as a read-only property (instead of a method), "getter:" must be prepended. Various examples can be found in SE-0044 Import as member.

So the correct syntax to expose the C function as a (read-only) property to Swift is

NSString *myEnumString(MyEnum val)
NS_SWIFT_NAME(getter:MyEnum.stringVal(self:));

The generated Swift interface is

extension MyEnum {
    public var stringVal: String { get }
}

and this compiles and runs as expected in my test:

print(MyEnum.case1.stringVal)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382