Swift Enum
An enum in Swift defines a common type for a related group of values. You declare an enumeration with the enum keyword and use its cases as type-safe values throughout your program.
Enums are useful when a value must be selected from a known set of possibilities, such as weekdays, directions, application states, or network response results.
What Is an Enumeration in Swift?
An enumeration, commonly called an enum, groups related named values into a new Swift type. Each named value is called a case.
Unlike enumerations in some programming languages, Swift enum cases do not automatically receive integer values. Cases are distinct values of the enum type unless you explicitly assign raw values.
For example, an enum named Direction may contain the cases north, south, east, and west. A variable of type Direction can then hold only one of those cases.
Syntax of Enum in Swift
The syntax to declare an enum is:
enum enumName {
// enumerated elements
}
where enumName is the name by which we can reference this enum.
Inside the curly braces, you can declare the elements, one for each line. For each element you declare, you should provide the keyword case prior to the element name. An example is shown below.
enum enumName {
case Element1
case Element2
}
You can declare as many number of elements inside Enum as per requirement.
Swift naming conventions generally use an uppercase name for the enum type and lower camel case for its cases. Multiple cases may also be declared on one line.
enum Direction {
case north, south, east, west
}
Create and Assign Swift Enum Values
Access an enum case by writing the enum type followed by the case name.
enum Direction {
case north, south, east, west
}
var currentDirection = Direction.north
After Swift has inferred the variable’s enum type, you can use the shorter dot syntax when assigning another case.
currentDirection = .west
The leading dot is sufficient because Swift already knows that currentDirection has the type Direction.
Example 1 – Swift Enum
In this example, we will write an enum to declare days of week as elements. We will use switch case to demonstrate the usage of enum.
main.swift
enum WeekDay {
case Monday
case Tuesday
case Wednesday
case Thursday
case Friday
case Saturday
case Sunday
}
func action(day: WeekDay){
switch day{
case .Monday:
print("Monday is working day. Go to office.")
case .Tuesday:
print("Tuesday is working day. Go to office.")
case .Wednesday:
print("Wednesday is working day. Go to office.")
case .Thursday:
print("Thursday is working day. Go to office.")
case .Friday:
print("Friday is status day. Prepare stutus presentation for office.")
case .Saturday:
print("Saturday is off day. Rest at home.")
case .Sunday:
print("Sunday is off day. Rest at home.")
}
}
let today = WeekDay.Thursday
action(day:today)
action(day:WeekDay.Friday)
action(day:WeekDay.Saturday)
Output
Thursday is working day. Go to office.
Friday is status day. Prepare stutus presentation for office.
Saturday is off day. Rest at home.
The action(day:) function accepts only a WeekDay value. The switch statement handles every case, so a separate default branch is not required.
Use a Switch Statement with a Swift Enum
A switch statement is commonly used with enums because it can match each possible case. Swift requires a switch to be exhaustive, which means every possible enum case must be handled.
enum TrafficLight {
case red, yellow, green
}
let signal = TrafficLight.red
switch signal {
case .red:
print("Stop")
case .yellow:
print("Prepare to stop")
case .green:
print("Go")
}
Output
Stop
If every case is listed explicitly, the compiler can identify missing cases when the enum is changed later. A default branch may be used when several cases should share the same behavior, but explicit cases provide stronger compile-time checking.
Swift Enum with Raw Values
A Swift enum can store a predefined raw value for each case. Common raw-value types include String, Character, and numeric types such as Int.
enum HTTPStatus: Int {
case success = 200
case notFound = 404
case serverError = 500
}
let status = HTTPStatus.notFound
print(status.rawValue)
Output
404
For an integer-backed enum, Swift can automatically increment omitted raw values from the preceding value.
enum Priority: Int {
case low = 1
case medium
case high
}
print(Priority.medium.rawValue)
print(Priority.high.rawValue)
Output
2
3
When the raw-value type is String and no explicit value is supplied, each case name becomes its raw value.
enum FileType: String {
case pdf
case image
case text
}
print(FileType.image.rawValue)
Output
image
Create a Swift Enum from a Raw Value
Swift provides a raw-value initializer for enums that declare raw values. The initializer returns an optional because the supplied value may not match any case.
enum HTTPStatus: Int {
case success = 200
case notFound = 404
case serverError = 500
}
if let status = HTTPStatus(rawValue: 404) {
print(status)
} else {
print("Unknown status")
}
Output
notFound
For example, HTTPStatus(rawValue: 201) returns nil because the enum does not declare a case with that raw value.
Swift Enum with Associated Values
Associated values allow each enum instance to store additional data. Different cases can store different types and amounts of information.
enum PaymentResult {
case success(transactionID: String)
case failure(message: String)
}
let result = PaymentResult.success(transactionID: "TXN-1042")
switch result {
case .success(let transactionID):
print("Payment completed: \(transactionID)")
case .failure(let message):
print("Payment failed: \(message)")
}
Output
Payment completed: TXN-1042
Here, the success case carries a transaction identifier, while the failure case carries an error message. The stored value is extracted through pattern matching in the switch statement.
Raw Values and Associated Values in Swift Enums
| Feature | Raw value | Associated value |
|---|---|---|
| Purpose | Assigns a fixed value to each case | Stores data with a particular enum instance |
| Defined | When the enum is declared | When the enum value is created |
| Value type | All cases use the declared raw-value type | Each case may use different value types |
| Access | Use the rawValue property | Extract with pattern matching |
| Example | case notFound = 404 | case failure(message: String) |
Raw values and associated values solve different problems. A raw value is a permanent representation of a case, while an associated value is instance-specific information carried by the case.
Add Properties and Methods to a Swift Enum
Swift enums can contain computed properties and methods. This keeps behavior that belongs to the enum close to its cases.
enum TemperatureUnit {
case celsius
case fahrenheit
var symbol: String {
switch self {
case .celsius:
return "°C"
case .fahrenheit:
return "°F"
}
}
func describe(value: Double) -> String {
return "\(value)\(symbol)"
}
}
print(TemperatureUnit.celsius.describe(value: 24))
Output
24.0°C
The keyword self refers to the current enum value. In the computed property, it is used to return the correct symbol for each case.
Iterate over Swift Enum Cases with CaseIterable
An enum without associated values can adopt the CaseIterable protocol. Swift then provides an allCases collection containing every case in declaration order.
enum CompassPoint: CaseIterable {
case north, south, east, west
}
for point in CompassPoint.allCases {
print(point)
}
Output
north
south
east
west
This is useful for building menus, test data, picker options, and other interfaces that need every enum case.
Recursive Enums with the Indirect Keyword
A recursive enum has a case whose associated value contains another value of the same enum type. Mark the recursive case with indirect, or place indirect before the enum declaration when all cases may be recursive.
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
}
let expression = ArithmeticExpression.addition(
.number(4),
.number(6)
)
Recursive enums are commonly used to represent tree-like data, including arithmetic expressions, syntax trees, and nested structures.
When to Use an Enum in Swift
- Use an enum when a value must be one of a fixed set of named choices.
- Use raw values when each case needs a stable string, character, or numeric representation.
- Use associated values when each enum instance must carry additional data.
- Use methods and computed properties when behavior belongs directly to the cases.
- Use
CaseIterablewhen the program needs to process every case. - Use a recursive enum when modeling nested or tree-shaped data.
An enum is usually clearer than unrelated strings or integers because the compiler checks that only valid cases are assigned and handled.
Common Swift Enum Mistakes
- Assuming cases automatically have integer values: Swift cases have no raw value unless a raw-value type is declared.
- Forgetting that raw-value initialization is optional:
EnumType(rawValue:)can returnnil. - Confusing raw and associated values: raw values are fixed, while associated values are supplied when an instance is created.
- Leaving a switch incomplete: every possible case must be handled unless a suitable
defaultbranch is present. - Using strings where an enum is safer: arbitrary strings allow spelling errors and unsupported values that an enum prevents.
Swift Enum Frequently Asked Questions
Do Swift enum cases automatically have integer values?
No. Swift enum cases are independent values and do not receive implicit integers by default. To associate integers with cases, declare the enum with an Int raw-value type.
Can a Swift enum store additional data?
Yes. An enum case can store one or more associated values. Different cases in the same enum may store different types of data.
Why does enum initialization from a raw value return an optional?
The supplied raw value may not correspond to any declared case. Swift therefore returns either a matching enum value or nil.
Can Swift enums contain methods and properties?
Yes. Swift enums can define instance methods, static methods, computed properties, initializers, and protocol conformances.
How do you list every case of a Swift enum?
Make the enum conform to CaseIterable, and then access the generated allCases collection. Automatic synthesis is generally available for enums whose cases do not contain associated values.
Swift Enum Summary
Swift enums create type-safe groups of related cases. They can be matched exhaustively with switch, assigned raw values, supplied with associated values, extended with properties and methods, and made iterable with CaseIterable. In this Swift Tutorial, we learned how to declare and use enumerations in Swift programming.
TutorialKart.com