Using enum from Objective C in Swift

Reading time ~1 minute

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.

kiwi campus

가족여행차 샌 프란시스코에 갔다가 오랜만에 버클리 교정을 구경하러 갔다.돌아다니다보니 Sather gate 근처의 분수대 주변에 이런 게 돌아다니고 있었다.처음엔 학생이 만든 장난감 정도로 생각했다. 폰에 외장(?)렌즈를 달아서 꽂아놨는데 이게 ...… Continue reading