Why NS_TYPED_ENUM is the future

Derrick Ho
2 min readJan 28, 2018

As a working professional iOS developer, you have undoubtedly needed to use both Objective-C and Swift in the same package. And almost like it was fate, you would need to use global strings. Maybe this is for a user facing string or maybe it is something internal like your public key to a 3rd party API.

Regardless of the reason, global constant strings are needed and to keep Objective-C/Swift compatibility you would need to use NS_STRING_ENUM to make a group of Objective-C global strings available to Swift files. It would be nice if you could write this piece in Swift and have it compatible with Objective-C, but as far as I know there isn’t a way.

// Something.h
typedef NSString * Traffic NS_STRING_ENUM;
static Traffic const TrafficRed = @"Red";
static Traffic const TrafficYellow = @"Yellow";
static Traffic const TrafficGreen = @"Green";

By adding NS_STRING_ENUM, the compiler exposes these three traffic lights as a struct

struct Traffic {
let rawValue: String
static let red = Traffic(rawValue: "Red")
static let yellow = Traffic(rawValue: "Yellow")
static let green = Traffic(rawValue: "Green")
}

As of Swift 4, there is a new attribute that supplants NS_STRING_ENUM, and it is called NS_TYPED_ENUM. Believe me, it is the future.

Did you know that you can use more then just Global Strings?

How about some numbers?

// SomeNum.h
typedef NSInteger SomeNum NS_TYPED_ENUM;
static SomeNum const SomeNumOne = 0x01 << 0;
static SomeNum const SomeNumTwo = 0x01 << 1;
static SomeNum const SomeNumFour = 0x01 << 2;

This will translate to swift as:

struct SomeNum {
let rawValue: Int
static let one = SomeNum(rawValue: 0b001)
static let two = SomeNum(rawValue: 0b010)
static let four = SomeNum(rawValue: 0b100)
}

How about some arrays?

// SomeArrays.h
typedef NSInteger NumberCombo [3] NS_TYPED_ENUM;
static NumberCombo const NumberComboAlpha = {1,2,3};
static NumberCombo const NumberComboBeta = {4,5,6};

This will translate to swift as:

struct SomeArrays {
let rawValue: (Int, Int, Int)
static let alpha = SomeArrays(rawValue: (1,2,3))
static let beta = SomeArrays(rawValue: (4,5,6))
}

Why is NS_TYPED_ENUM the future? Well, because it’s more than just global strings.

--

--