1

I store constants in a objective-c header file as suggested here. I define a NS_ENUM and also a constant array which works nicely in objective-c e.g. SDModeString(kSDOne). However, I cant get this to work called from Swift. I am sure I am doing something very stupid here, but a suggestion for how to call SDModeString from Swift would be appreciated. I can get access to SDMode but not SDModeString. Thanks.

typedef NS_ENUM(NSInteger, SDMode) {
    kSDOne, kSDTwo, kSDThree
};
#define SDModeString(SDMode) [@[@"kSDOne",@"kSDTwo",@"kSDThree"]     objectAtIndex:SDMode]
Community
  • 1
  • 1
Trond Kristiansen
  • 2,379
  • 23
  • 48

1 Answers1

4

You need to turn SDModeString into a proper function, like so:

inline NSString *SDModeString(enum SDMode mode) {
  return [@[ @"kSDOne", @"kSDTwo", @"kSDThree" ] objectAtIndex:mode];
}

though I would probably just use a switch, faster, safer etc:

inline NSString *SDModeString(enum SDMode mode) {
  switch (mode) {
    case kSDOne:   return @"kSDOne";
    case kSDTwo:   return @"kSDTwo";
    case kSDThree: return @"kSDThree";
    default: assert(false);
  }
}
hnh
  • 13,957
  • 6
  • 30
  • 40
  • 2
    Also, I would name the function `NSStringFromSMMode` because that's what Apple API is using. – Sulthan Nov 30 '16 at 14:34
  • @Sulthan That's actually a decent reason _not_ to name it that — Apple reserves two-letter prefixes for itself, so it's conceivable that if they had a framework whose prefix is `SD` and they had an `SDMode`, this is what they'd name their own function. You'd then be conflicting with them, and get linker errors. It's safer to call it this, or `SDStringFromMode`, or similar. – Itai Ferber Nov 30 '16 at 15:49
  • 1
    @ItaiFerber If you consider this a problem, then the correct solution is to change your `SD` prefixes to a three letter prefix, not to think up alternative function names because `SDMode` enum will be already causing a name conflict. – Sulthan Nov 30 '16 at 15:56
  • @Sulthan True, but changing your codebase in this way may not be feasible, depending on how big your project is, how much legacy you've got, etc. There's no real reason not to be proactive about this going forward, doing what you can to prevent future headache for yourself. – Itai Ferber Nov 30 '16 at 16:03