Blog / April 17, 2023 / 4 mins read / By Mahi Garg

Enums in Swift

When it comes to writing clean, maintainable, and bug-free code, Swift provides a powerful feature called enums or enumerations. Enums are a fundamental data type that allows developers to define a set of related values in a type-safe manner. They play a significant role in improving code readability, eliminating runtime errors, and enhancing overall code quality. In this blog, we’ll delve into the world of enums in Swift and explore how they can level up your coding game with some practical examples.

What are Enums?

Enums, short for enumerations, are a way to define a group of related values in Swift. With enums, you can define a finite set of possible values that a variable can take, and Swift ensures that only those predefined values can be assigned to the variable. This type safety helps catch errors at compile-time, making your code more robust.

Declaring Enums

Let’s start with a simple example of an enum representing different types of fruits:

enum Fruit {
    case apple
    case banana
    case orange
    case mango
}

In this example, we’ve declared an enum called Fruit with four cases: apple, banana, orange, and mango. Each case represents a distinct value that a variable of type Fruit can hold.

Using Enums

Now that we have our Fruit enum, let’s see how we can use it in our code:

var favoriteFruit = Fruit.apple
print("My favorite fruit is \(favoriteFruit)")

favoriteFruit = .mango
print("I changed my mind, now my favorite fruit is \(favoriteFruit)")

The output will be:

My favorite fruit is apple
I changed my mind, now my favorite fruit is mango

As you can see, we can create a variable favoriteFruit of type Fruit and assign it a value from the enum cases. Once a variable is assigned an enum value, it can only be changed to another value from the same enum.

Associated Values

Enums can also have associated values, which allow us to attach additional information to each case. This feature is particularly useful when a case needs to carry some data along with it. Let’s take the example of a Measurement enum:

enum Measurement {
    case length(Double)
    case weight(Double)
    case temperature(Double)
}

Here, we’ve defined three cases: length, weight, and temperature, and each case has an associated Double value representing the measurement in meters, kilograms, and degrees Celsius, respectively.

Enum with Associated Values Example

func describe(measurement: Measurement) -> String {
    switch measurement {
    case let .length(value):
        return "The length is \(value) meters."
    case let .weight(value):
        return "The weight is \(value) kilograms."
    case let .temperature(value):
        return "The temperature is \(value) degrees Celsius."
    }
}

let lengthMeasurement = Measurement.length(5.3)
let weightMeasurement = Measurement.weight(68.2)
let temperatureMeasurement = Measurement.temperature(25.0)

print(describe(measurement: lengthMeasurement))
print(describe(measurement: weightMeasurement))
print(describe(measurement: temperatureMeasurement))

Output:

The length is 5.3 meters.
The weight is 68.2 kilograms.
The temperature is 25.0 degrees Celsius.

Raw Values

In addition to associated values, enums in Swift can also have raw values. Raw values are pre-defined values that are implicitly assigned to each enum case. Raw values must have the same data type, and each case’s raw value must be unique within the enum. Raw values are particularly useful when working with external data formats or APIs that expect specific values.

Here’s an example of an enum representing the days of the week using raw values:

enum Weekday: String {
    case sunday = "Sun"
    case monday = "Mon"
    case tuesday = "Tue"
    case wednesday = "Wed"
    case thursday = "Thu"
    case friday = "Fri"
    case saturday = "Sat"
}

Enum with Raw Values Example

let today = Weekday.friday
print("Today is \(today.rawValue)")

Output:

Today is Fri

Iterating over Enum Cases

Sometimes, you may need to iterate over all the cases of an enum, especially when you have a large number of cases or when you’re working with generic code. Swift allows you to do this using the CaseIterable protocol.

enum Direction: CaseIterable {
    case north
    case south
    case east
    case west
}

for direction in Direction.allCases {
    print(direction)
}

Output:

north
south
east
west

Conclusion

Enums in Swift are a powerful tool for creating well-structured, type-safe code. By using enums, you can represent a fixed set of related values, attach additional data to each case, and handle different scenarios more elegantly. Whether you’re working with UI elements, API responses, or any other use case, enums will undoubtedly enhance your code’s clarity and maintainability.

So, the next time you find yourself dealing with a set of related values, consider reaching for enums to make your Swift code more expressive and robust! Happy coding! 🚀

Comments