4

How to forward declare NS_OPTIONS in Objective-C?

Related SO question for NS_ENUMS: Forward-declare enum in Objective-C

Unanswered question on Apple Dev Forum: https://forums.developer.apple.com/thread/16305

typedef NS_OPTIONS(NSInteger, MSSOption) {
    MSSOptionNone       = 0,
    MSSOptionName       = 1 << 0,
    MSSOptionEmail      = 1 << 1,
    MSSOptionTelephone  = 1 << 2
};
dan1st
  • 12,568
  • 8
  • 34
  • 67
foobar
  • 133
  • 1
  • 7
  • 1
    Possible duplicate of [Forward-declare enum in Objective-C](https://stackoverflow.com/questions/946489/forward-declare-enum-in-objective-c) – Cœur May 24 '18 at 08:22

1 Answers1

5

Strictly the same as for NS_ENUM, so the answers from Forward-declare enum in Objective-C are all valid.

To forward declare your NS_OPTIONS, you have two solutions:

solution 1

typedef NS_ENUM(NSInteger, MSSOption);

solution 2

typedef NS_OPTIONS(NSInteger, MSSOption);

Both solutions work fine. Tested with Xcode 9.3.1 and Xcode 10.1.
Demonstration at https://github.com/Coeur/StackOverflow50499172.

Community
  • 1
  • 1
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Did you actually try this? For solution 1 I get "Redefinition with different type" and for solution 2 I get "The declaration does not declare anything". This is with Xcode 10.1. Maybe things changed since you tried it? – Baxissimo Dec 18 '18 at 00:47
  • @Baxissimo it works perfectly with Xcode 10.1 too. Demonstration at https://github.com/Coeur/StackOverflow50499172. You're probably just doing something else wrong. – Cœur Dec 18 '18 at 11:35
  • 1
    Yeh, your sample does seem to work fine. Not sure what the difference is. I tried to change the setup in your code to be more like in our app, but all such mods worked fine. Maybe I had one as NSInteger and the other as NSUInteger. That would explain the "different type" error I got. Though I thought I triple checked that the type for both declarations was the same. Unfortunately I've lost the place in our app I was trying to do this. It was in the middle of a bunch of refactoring that I hit upon it. – Baxissimo Dec 20 '18 at 16:54
  • @Baxissimo were you able to spot the difference? I have same problem, that NS_OPTIONS gave me "declaration doesn't declare anything" and NS_ENUM - redefinition error. – Crazy Sage Feb 22 '22 at 09:03
  • @CrazySage could it be that the name is already taken? Try to change your typedef to a different name. If that doesn't solve it, maybe check that you're using `#import` on your headers and not `#include`? – Cœur Feb 23 '22 at 09:11