A large portion of code in my current project is written in Swift and I’m using Swift for all my new code. Then today, I happened to modify a class written in Objective C.
What I wanted were an enum for representing some states and a method that handles the states in the class.
Assume that a new enum and a method that takes it as a parameter are defined in an Objective C source file as follows;
typedef NS_ENUM(NSInteger, MyEnumType) {
MyEnumTypeFirst,
MyEnumTypeSecond
};
- (void)saveMyEnumType:(MyEnumType) mode {
...
}
(Apple recommends to use NS_ENUM.)
And then I tried to access them from a Swift class but their names didn’t show up on auto-complete suggestion. However, when I looked close, I could find the enum elements without a prefix MyENumType
in the suggestion; first
and second
which were originally defined as MyEnumTypeFirst
, MyEnumTypeSecond
respectively in Objective C code. Swift bridge automatically got rid of prefix MyEnumType
from the Objective C’s enum and provided a convinient way to use them.
So the enums can be used like this in a switch statement;
// value is MyEnumType
switch value {
case .first:
...
case .second:
...
}
And the method turned into like this;
// declared as saveMyEnumType in Objective C
save(_ mode: MyEnumType)
We can call the method like save(value)
instead of saveMyEnumType(value)
. Simple and concise.