When writing enumerations in Objective-C, you can do something like this with the NS_ENUM
macro which supports specifying the prefix to be dropped:
typedef NS_ENUM(NSInteger, SomeEnumType) {
SomeEnumTypeValueOne,
SomeEnumTypeValueTwo,
SomeEnumTypeValueThree
};
In Swift, you can access them because they are imported as native Swift enumerations:
var x = SomeEnumType.Two
switch (x) {
case .One:
NSLog("One")
default:
NSLog("Something else")
}
But if you have a enumeration already defined in existing Objective-C code like this:
enum SomeEnumType {
SomeEnumTypeValueOne,
SomeEnumTypeValueTwo,
SomeEnumTypeValueThree
};
You can still use them in Swift like this:
var x = SomeEnumTypeValueOne
switch (x.value) {
case SomeEnumTypeValueOne.value:
NSLog("hello")
default:
NSLog("hey")
}
On the other hand, if you define an enumeration in Swift and want to be able to use it from Objective-C, use @objc
attribute like this:
@objc enum Directions: Int {
case North
case South
case East
case West
}
which would be the equivalent of this in Objective-C:
typedef NS_ENUM(NSInteger, Directions) {
DirectionsNorth,
DirectionsSouth,
DirectionsEast,
DirectionsWest
};
Your feedback is valuable: Do you want more nuggets like this? Yes or No
.
.