How to Use Enums in Swift

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
April 15, 2023

How to Use Enums in Swift

Enums, or enumerations, are a powerful feature in Swift that allows you to define a set of related values as a single type. Enums can be used to represent a set of options or states, and can make your code more readable and easier to maintain.

Creating an Enum

To create an enum in Swift, use the enum keyword followed by the name of the enum. Inside the curly braces, you define the possible cases of the enum as comma-separated values:

enum Planet {
    case mercury
    case venus
    case earth
    case mars
    case jupiter
    case saturn
    case uranus
    case neptune
}

In this example, we've defined an enum called Planet with possible cases for each of the eight planets in our solar system.

Using an Enum

Once you've defined an enum, you can use it to define variables or parameters with the enum type:

var favoritePlanet: Planet = .earth

In this example, we've defined a variable called favoritePlanet of type Planet. We've set the initial value to .earth, which is a case of the Planet enum.

You can also use enums in switch statements to handle different cases:

func planetDescription(planet: Planet) -> String {
    switch planet {
    case .mercury:
        return "The smallest planet in the solar system"
    case .venus:
        return "The hottest planet in the solar system"
    case .earth:
        return "The only known planet with life"
    case .mars:
        return "Also known as the Red Planet"
    case .jupiter:
        return "The largest planet in the solar system"
    case .saturn:
        return "Famous for its rings"
    case .uranus:
        return "The first planet discovered using a telescope"
    case .neptune:
        return "The farthest planet from the Sun"
    }
}

let description = planetDescription(planet: .mars)
print(description) // Outputs "Also known as the Red Planet"

In this example, we've defined a function called planetDescription that takes a parameter of type Planet. In the switch statement inside the function, we handle each possible case of the enum and return a description of the planet. We then call the function with an argument of .mars and print the result.

Conclusion

Enums are a powerful feature in Swift that can make your code more readable and easier to maintain. Using enums allows you to define a set of related values as a single type, and switch statements can be used to handle different cases of the enum. Try using enums in your next Swift project to see how they can simplify your code.