GarethPrice
GarethPrice

Reputation: 1104

Objective-C enum in Swift

I have the following enum in an Objective-C file:

typedef NS_ENUM(NSInteger, countDirection){
    countDirectionUp = 0,
    countDirectionDown
};

How can I use this in a Swift view controller? I have tried this:

label.countDirection = countDirection.countDirectionDown

but I get an error:

countDirection.Type does not have a member named countDirectionDown

Upvotes: 10

Views: 9236

Answers (2)

gnasher729
gnasher729

Reputation: 52622

These get translated to

countDirection.Up
countDirection.Count

Swift removes as many letters as possible that the enum values have in common with the enumeration name. In your case, with an enumeration called countDirection and a value countDirectionUp, the whole "countDirection" is removed. It's not needed because you know which enum you are using, making your code considerable shorter.

Upvotes: 19

7stud
7stud

Reputation: 48649

With a bridging header and your enum values, I get the same error you do. However, if I change the enum values to:

typedef NS_ENUM(NSInteger, countDirection) {
    cdUp = 0,
    cdDown

};

...then I don't get any errors. For some reason, Swift does not like enum values that begin with the type name.

No error with these enum values either:

typedef NS_ENUM(NSInteger, countDirection) {
    CountDirectioUp = 0,
    CountDirectionDown
};

Upvotes: 3

Related Questions