GeneCode
GeneCode

Reputation: 7588

Typedef enum declaration: which is correct

So I been used to use this format to declare a enum types:

typedef enum SortType {
    SORT_BY_NAME,
    SORT_BY_COMPANY,
    SORT_BY_NONE
} SortType;

But I saw some people declare it this way

typedef enum {
    SORT_BY_NAME,
    SORT_BY_COMPANY,
    SORT_BY_NONE
} SortType;

Both seems to work and no error. But I want to know which is correct.

Upvotes: 0

Views: 67

Answers (2)

Cezar
Cezar

Reputation: 56332

Between those two, there isn't a wrong form per se. That said, the current recommended way to declare enums in Objective-C is using the NS_ENUM macro:

typedef NS_ENUM(NSInteger, SortType) {
    SORT_BY_NAME,
    SORT_BY_COMPANY,
    SORT_BY_NONE
};

From Apple's Adopting Modern Objective-C guide:

The NS_ENUM and NS_OPTIONS macros provide a concise, simple way of defining enumerations and options in C-based languages. These macros improve code completion in Xcode and explicitly specify the type and size of your enumerations and options. Additionally, this syntax declares enums in a way that is evaluated correctly by older compilers, and by newer ones that can interpret the underlying type information.

Use the NS_ENUM macro to define enumerations, a set of values that are mutually exclusive:

The NS_ENUM macro helps define both the name and type of the enumeration, in this case named UITableViewCellStyle of type NSInteger. The type for enumerations should be NSInteger.

Upvotes: 0

CyberMoai
CyberMoai

Reputation: 506

I would recommend:

typedef NS_ENUM(NSInteger, SortType) {
    SortTypeName,
    SortTypeCompany,
    SortTypeNone
};

as per the Apple Developer Guides and Sample Code: Adopting Modern Objective-C > Enumeration Macros

Upvotes: 3

Related Questions