Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 575
GarethPrice Avatar asked Jul 24 '15 05:07

GarethPrice


People also ask

Can we use Swift enum in Objective-C?

Event though Swift supports string enums they cannot be used in Objective-C, only Int enums are allowed.

What is enum in Objective-C?

typedef enum declaration in Objective-CA enum declares a set of ordered values - the typedef just adds a handy name to this. The 1st element is 0 etc. typedef enum { Monday=1, Tuesday, Wednesday } WORKDAYS; WORKDAYS today = Monday;//value 1.

What is Ns_closed_enum?

When you use NS_CLOSED_ENUM , you are making a promise to consumers of your API that the enum will never change, either now in the future. Of course, there is nothing stopping you from making that change, but if you do, you've now broken that promise. As you said, it compiles fine after updating the switch cases.

How do I import a Swift file into Objective-C?

Import Swift code into Objective-C within the same framework: Under Build Settings, in Packaging, make sure the Defines Module setting for that framework target is set to Yes. Import the Swift code from that framework target into any Objective-C .


2 Answers

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.

like image 179
gnasher729 Avatar answered Oct 02 '22 13:10

gnasher729


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
};
like image 29
7stud Avatar answered Oct 02 '22 15:10

7stud