Declaring Enums in Swift: A Comprehensive Guide to Get Started
Swift is a powerful, modern programming language used to create applications for iOS, macOS, watchOS, and tvOS. It is also known for its robust type system, which allows developers to easily define and use custom data structures. One of these data structures is the enum, or enumeration.
Enums are a special type of value that represent a set of related values. For example, an enum can be used to represent the days of the week, the suits of a deck of cards, or the types of error a program may encounter. They are commonly used to model data that has a small, fixed number of possible values.
In this article, we’ll explore how enums work in Swift and how to use them effectively in your own projects. We’ll start by looking at the basic syntax for declaring enums, then move on to some more advanced concepts like associated values and raw values.
Declaring an Enum
The most basic way to declare an enum is with the `enum` keyword followed by a name for the enum and a list of cases. Here’s an example of an enum that represents the days of the week:
enum DaysOfTheWeek {
case Sunday
case Monday
case Tuesday
case Wednesday
case Thursday
case Friday
case Saturday
}
This code declares a new enum called `DaysOfTheWeek` that contains seven cases representing each day of the week.
You can also declare enums with multiple lines of code. This is useful if you want to add additional information to each case. For example, here’s an enum that stores information about the suit of a card in a deck of cards:
enum CardSuit {
case Spades(String)
case Hearts(String)
case Diamonds(String)
case Clubs(String)
}
This code declares an enum called `CardSuit` with four cases, each containing a string value. We can use this string value to store information about the suit, such as its color or symbol.
Using an Enum
Once you’ve declared an enum, you can use it to create variables and constants. Here’s an example of creating a variable with the `DaysOfTheWeek` enum we declared earlier:
var today = DaysOfTheWeek.Monday
This code creates a variable called `today` and assigns it the value `Monday`. You can also create constants with enum values, like this:
let weekend = [DaysOfTheWeek.Saturday, DaysOfTheWeek.Sunday]
This code creates a constant called `weekend` and assigns it an array containing the enum values `Saturday` and `Sunday`.
Enums can also be used in switch statements. This is useful for handling different cases in a program. For example, here’s a switch statement that uses the `CardSuit` enum we declared earlier:
switch card.suit {
case .Spades(let symbol):
print("This card is a spade with the symbol \(symbol)")
case .Hearts(let symbol):
print("This card is a heart with the symbol \(symbol)")
case .Diamonds(let symbol):
print("This card is a diamond with the symbol \(symbol)")
case .Clubs(let symbol):
print("This card is a club with the symbol \(symbol)")
}
This code uses a switch statement to handle four different cases. Each case prints out a message with the card’s suit and symbol.
Associated Values
One of the most powerful features of enums in Swift is the ability to associate values with each case. This allows you to store additional information with each enum value. For example, here’s an enum that stores the temperature in both Celsius and Fahrenheit:
enum Temperature {
case Celsius(Double)
case Fahrenheit(Double)
}
This code declares an enum called `Temperature` with two cases, each containing a double value. This allows us to store the temperature in both Celsius and Fahrenheit.
We can use associated values in switch statements, just like any other enum value. Here’s an example of a switch statement that uses the `Temperature` enum we declared earlier:
switch temperature {
case .Celsius(let celsius):
print("The temperature is \(celsius) degrees Celsius")
case .Fahrenheit(let fahrenheit):
print("The temperature is \(fahrenheit) degrees Fahrenheit")
}
This code uses a switch statement to handle two different cases. Each case prints out a message with the temperature in either Celsius or Fahrenheit.
Raw Values
Another powerful feature of enums in Swift is the ability to assign raw values to each case. This allows you to assign a specific value to each case, such as a string or integer. For example, here’s an enum that stores the types of errors a program may encounter:
enum ErrorType: String {
case NotFound = "Error: Not Found"
case InternalError = "Error: Internal Error"
case Unauthorized = "Error: Unauthorized"
}
This code declares an enum called `ErrorType` with three cases, each containing a string value. This allows us to easily compare the enum value against a string to determine the type of error.
We can also use raw values in switch statements. Here’s an example of a switch statement that uses the `ErrorType` enum we declared earlier:
switch error {
case .NotFound:
print("The requested resource could not be found")
case .InternalError:
print("An internal error occurred")
case .Unauthorized:
print("You are not authorized to access this resource")
}
This code uses a switch statement to handle three different cases. Each case prints out a message with the appropriate error message.
Conclusion
Enums are a powerful tool in Swift for defining custom data structures. They allow you to declare a set of related values and easily compare them against each other. They also support associated values and raw values, which allow you to store additional information with each enum value.
By understanding how enums work and how to use them effectively, you can take advantage of their powerful features to create more robust and maintainable code.