Add macros to your Objective-C types to group their values in Swift.
- Swift Standard Library
You use one of the following macros to declare that several Objective-C constants are related to each other:
NSfor simple enumerations
NSfor enumerations whose cases can be grouped into sets of options
NSfor enumerations with a raw value type that you specify
NSfor enumerations that you expect might gain more cases
_TYPED _EXTENSIBLE _ENUM
Declare Simple Enumerations
NS macro for simple groups of constants.
The example below uses the macro to declare a
UITable enumeration that groups several different view styles for table views:
In Swift, the
UITable enumeration is imported like this:
Enumerations imported using the
NS macro won't fail when you initialize one with a raw value that does not correspond to an enumeration case. This characteristic facilitates compatibility with C, which allows any value to be stored in an enumeration, including values used internally but not exposed in headers.
NS macro is the only enumeration macro that results in an actual enumeration type when imported to Swift. The other enumeration macros generate structures.
Declare Option Sets
You use the
NS macro when two or more constants in a grouping of constants can be combined. For example, the output formatting for a
JSONEncoder instance can be sorted and can use ample white space at the same time, so it's valid to specify both options in an option set:
The example below shows how to apply the
NS macro and assign raw values that are mutually exclusive:
The increasing sequence of nonnegative integers used along with the bitwise left shift operator (
<<) ensures that each option in the option set takes up a unique bit in the binary representation of the raw value.
Here's how the
UIView type is imported to Swift:
Declare Typed Enumerations
You use the
NS to group constants with a raw value type that you specify. Use
NS for sets of constants that can't logically have values added in a Swift extension, and use
NS for sets of constants that can be expanded in an extension.
The example below uses the
NS macro to declare the different colors used by a traffic light:
The number of colors that a traffic light uses isn't expected to grow, so it's not declared to be extensible.
Here's how the
Traffic type is imported to Swift:
Declare Typed Extensible Enumerations
Extensible enumerations are imported in a similar fashion to nonextensible ones, except that they receive an additional initializer.
The examples below show how a
Favorite type is declared, imported, and extended. The first one declares the
Favorite type and adds a single enumeration case for the color blue:
The additional initializer omits the label requirement for its first parameter:
You can add extensions to extensible enumerations later in your Swift code.
The example below adds another favorite color: