2

I have an enum defined like this:

typedef enum dataTypes{
    LOW,
    MEDIUM,
    HIGH,
    MAX_DATA_TYPE
} dataTypeEnum;

I'd like to be able to instantiate an NSArray of NSNumbers like so:

NSArray * numsToUse = @[@LOW, @MEDIUM];

This is not compiling. Any insights? Do I have to go with the clunkier [NSNumber numberWithInt:] for each of these or is there a way around this? (I have considered and rejected #define statements for a number of reasons).

jscs
  • 63,694
  • 13
  • 151
  • 195
helloB
  • 3,472
  • 10
  • 40
  • 87
  • You should use `typedef NS_ENUM(NSInteger, DataTypeEnum) {..}` to define your enum. – orkoden Dec 10 '15 at 16:32
  • @orkoden what is the difference and why is NS_ENUM preferable? – helloB Dec 10 '15 at 17:08
  • [See Apple's Docs](https://developer.apple.com/library/ios/releasenotes/ObjectiveC/ModernizationObjC/AdoptingModernObjective-C/AdoptingModernObjective-C.html) tl:dr better code completion, better type information for compiler, better Swift interop – orkoden Dec 10 '15 at 17:09

1 Answers1

5

You just need to use the expression syntax:

NSArray * numsToUse = @[@(LOW), @(MEDIUM)];
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • 5
    To add more info - the `@` syntax with no parentheses only works with number literals or `BOOL` literals. All other numeric expressions require the use of parentheses. – rmaddy Dec 10 '15 at 16:27
  • 2
    The "why" is that in parentheses the expression is evaluated and then the NSNumber boxing is applied. You can also do `@(1+1)`. – Rob Napier Dec 10 '15 at 16:39
  • Thanks to both of you for the clarification! – helloB Dec 10 '15 at 17:07
  • I want to add that the `@` syntax with no parentheses also works in front of macros that are defined to number literals. – newacct Dec 11 '15 at 01:27