Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources
Defining Enums in Swift

Defining Enums in Swift

What is an Enum?

An enum (short for enumeration) is a data type that consists of a set of named values called cases. Enums are a powerful feature in Swift that allow you to define a group of related values in a type-safe way. They can also have associated values and methods, making them extremely flexible and useful in many scenarios.

Defining an Enum

To define an enum in Swift, you use the enum keyword followed by the name of the enumeration and the cases it contains, enclosed in curly braces. Here is a simple example of an enum representing different types of beverages.

enum Beverage {

case coffee

case tea

case juice

}

In this example, we define an enum called Beverage with three cases: coffee, tea, and juice.

Using Enums

Once you have defined an enum, you can create instances of it. You can also use a switch statement to execute different code depending on the value of the enum. Here’s how you can use the Beverage enum defined earlier.

let myDrink = Beverage.coffee

switch myDrink {

case .coffee:

print("You chose coffee.")

case .tea:

print("You chose tea.")

case .juice:

print("You chose juice.")

}

In this example, we create an instance of Beverage called myDrink and assign it the value Beverage.coffee. The switch statement checks the value of myDrink and prints a message based on its value.

Enums with Associated Values

Enums can also store associated values, which allows you to attach additional information to each case. This is useful when you need to provide more context. Here’s an example of an enum that includes associated values.

enum Measurement {

case length(Double)

case weight(Double)

}

In this example, the Measurement enum has two cases: length and weight, each of which takes a Double value as an associated value. Here’s how you can use this enum.

let myLength = Measurement.length(42.0)

switch myLength {

case .length(let value):

print("Length is \(value) meters.")

case .weight(let value):

print("Weight is \(value) kilograms.")

}

Here, we create an instance of the Measurement enum with the case length and an associated value of 42.0. The switch statement then extracts the associated value and prints it.

Conclusion

Enums in Swift provide a way to define a group of related values and can have additional features such as associated values and methods. They improve code readability and maintainability by ensuring type safety. By understanding how to define and use enums, you can write cleaner and more expressive Swift code.