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
Event though Swift supports string enums they cannot be used in Objective-C, only Int enums are allowed.
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.
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.
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 .
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.
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With