Video
What are Enumerations
Enumerations, or enums for short, allow you to provide options as a data type. Each enumeration contains cases. Think of these cases like the choices to a multiple-choice question.
In this example, you can use an enumeration to store different blood types.
Why Enumerations?
You could get away with something like this:
However, using types like String
s to store values with pre-defined options can be dangerous. What if someone assigns you a blood type of C++???
With an enumeration, you can define what values a variable could possibly take.
Syntax & Conventions
In Swift, enumeration names are in PascalCase (first letter of each word is capitalized), because they are types. Each case is in camelCase, like variables.
Combining Cases
Multiple cases can be put on the same line and separated by commas.
Using Enumerations
You can get an enum value using the "full" declaration.
Like other types, you are able to use the explicit type declaration.
Using the explicit type declaration, you are also able to use the dot notation to select the case of the enum.
You can update the value with the dot notation, or the full form.
Enumerations in SwiftUI
Enumerations are often used within SwiftUI to provide options to a value. For example, when defining a font's design on a Text
, the Design
enum is used. This enumeration has 4 cases—default, monospaced, rounded, and serif.
Associated Values
Associated values can be used to store another value along with an enumeration case. You can pass in a value, or a tuple of multiple values as the associated value.
Associated values can be created with or without a parameter name.
In order to create an enumeration with an associated value, you will need to pass in the necessary values in.
Extracting Enumeration Associated Values
To retrieve the values, you will need to use a Switch Statement to extract the values into properties.
If you do not need a value, you can use an (_).
If you do not need any of the associated values, you can omit the segment within the brackets.
Raw Values
Enumeration cases can also be associated with a raw value.
These raw values can be accessible with the rawValue
property
You can also create an enum from a raw value.
In the example below, receivedStatusCode
is of the Optional StatusCode type (StatusCode?
). If a corresponding raw value cannot be found, it will return a nil value.
Implicit Raw Values
Raw values can also be defined implicitly. In this example, Day.sunday
's raw value is 0, Day.monday
's raw value is 1, and so on.