An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.If you are familiar with C, you will know that C enumerations assign related names to a set of integer values. Enumerations in Swift are much more flexible, and do not have to provide a value for each case of the enumeration. If a value (known as a “raw” value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type.
Enumeration Syntax
You introduce enumerations with the enum keyword and place their entire definition within a pair of braces:
enum SomeEnumeration {// enumeration definition goes here}
Here’s an example for the four main points of a compass:
enum CompassPoint {case northcase southcase eastcase west}
The values defined in an enumeration (such as
north, south, east, and west) are its enumeration cases. You use the case keyword to introduce new enumeration cases.
Multiple cases can appear on a single line, separated by commas:
enum Planet {case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune}
Each enumeration definition defines a brand new type. Like other types in Swift, their names (such as
types singular rather than plural names, so that they read as self-evident:
CompassPoint and Planet) should start with a capital letter. Give enumerationtypes singular rather than plural names, so that they read as self-evident:
var directionToHead = CompassPoint.west
The type of
directionToHead is inferred when it is initialized with one of the possible values of CompassPoint. Once directionToHead is declared as a CompassPoint, you can set it to a different CompassPoint value using a shorter dot syntax:directionToHead = .east
The type of
directionToHead is already known, and so you can drop the type when setting its value. This makes for highly readable code when working with explicitly typed enumeration values.
You can match individual enumeration values with a switch statement:
directionToHead = .southswitch directionToHead {case .north:print("Lots of planets have a north")case .south:print("Watch out for penguins")case .east:print("Where the sun rises")case .west:print("Where the skies are blue")}// Prints "Watch out for penguins"





Comments
Post a Comment