Enumerations

Last updated on 18 Oct 2024.

Written by Jia Chen.

Enumerations

Last updated on 18 Oct 2024.

Written by Jia Chen.

Enumerations

Last updated on 18 Oct 2024.

Written by Jia Chen.

Scroll Down

On this page

Video

On this page

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.

enum BloodType {
    case aPlus
    case aMinus
    case bPlus
    case bMinus
    case oPlus
    case oMinus
    case abPlus
    case abMinus
}

var bloodType = BloodType.oMinus

Why Enumerations?

You could get away with something like this:

var bloodType = "O-"

However, using types like Strings 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.

enum CompassPoint {
    case north
    case south
    case east
    case west
}

Combining Cases

Multiple cases can be put on the same line and separated by commas.

enum CompassDirection {
    case north, south, east, west
}

Using Enumerations

You can get an enum value using the "full" declaration.

var directionToGo = CompassDirection.east

Like other types, you are able to use the explicit type declaration.

let directionNotToGo: CompassDirection = CompassDirection.north

Using the explicit type declaration, you are also able to use the dot notation to select the case of the enum.

var anotherDirection: CompassDirection = .west

You can update the value with the dot notation, or the full form.

anotherDirection = .south
anotherDirection = CompassDirection.east

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.

Text("Hello, World!")
    .fontDesign(.monospaced)

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.

enum NetworkResult {
    case loading
    case success(String)
    case failure(error: String, statusCode: Int)
}

In order to create an enumeration with an associated value, you will need to pass in the necessary values in.

let result: NetworkResult = .success("Could not connect to server")
let anotherResult: NetworkResult = .failure(error: "I'm a teapot", statusCode: 418)

Extracting Enumeration Associated Values

To retrieve the values, you will need to use a Switch Statement to extract the values into properties.

switch result {
    case .loading: 
        print("Loading")
    case .success(let message): 
        print("Received: \(message)")
    case .failure(let error, let statusCode):
        print("Failed with \(error) and status code \(statusCode)")
}

If you do not need a value, you can use an (_).

switch result {
    case .loading: 
        print("Loading")
    case .success(let message): 
        print("Received: \(message)")
    case .failure(let error, _):
        print("Failed with \(error)")
}

If you do not need any of the associated values, you can omit the segment within the brackets.

switch result {
    case .loading: 
        print("Loading")
    case .success: 
        print("Success!")
    case .failure:
        print("Failed :(")
}

Raw Values

Enumeration cases can also be associated with a raw value.

enum StatusCode: Int {
    case notFound = 404
    case internalServerError = 500
    case imALittleTeapot = 418
}

These raw values can be accessible with the rawValue property

let statusCode = StatusCode.imALittleTeapot
print("Raw value: \(statusCode.rawValue)")

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.

let receivedStatusCode = StatusCode(rawValue: 404)
let anotherReceivedStatusCode = StatusCode(rawValue: 300) // nil

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.

enum Day: Int {
    case sunday
    case monday
    case tuesday
    case wednesday
    case thursday
    case friday
    case saturday
}

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.