Welcome to our Swift tutorial on Enum Cases! In this lesson, we'll explore how Enum (Enumeration) in Swift can be used to define a set of related values, and how we can create custom cases for them.
Enums, short for Enumerations, are a powerful feature in Swift that allows us to create custom data types. They can represent a collection of related values, such as the days of the week or the status of a user.
Let's start by creating a simple Enum. Open your Swift File and type:
enum WeekDay {
case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}In the above example, we've created an Enum called WeekDay with seven cases (Monday, Tuesday, etc.). Each case represents a day of the week.
Now that we have an Enum, we can use it in our code. Let's create a function that prints the current day:
func printCurrentDay(day: WeekDay) {
switch day {
case .Monday:
print("Today is Monday")
case .Tuesday:
print("Today is Tuesday")
// ... repeat for the other days
default:
print("Invalid day")
}
}In this function, we're taking an argument of type WeekDay. Inside the function, we use a switch statement to check the value of day. Depending on the value, we print the corresponding day of the week.
Enum cases can also have associated values, which allow us to attach additional data to each case. For example, let's modify our WeekDay Enum to include the number of each day:
enum WeekDay {
case Monday(Int), Tuesday(Int), Wednesday(Int), Thursday(Int), Friday(Int), Saturday(Int), Sunday(Int)
}
func printCurrentDay(day: WeekDay) {
switch day {
case let .Monday(number):
print("Today is Monday (\(number))")
// ... repeat for the other days
default:
print("Invalid day")
}
}In this modified example, each case now includes an associated value of type Int. We can access this value using the let keyword when we pattern match the case in the switch statement.
Swift also allows us to assign raw values to our Enum cases. Raw values can be of any type, but by default, they are integers. Let's modify our WeekDay Enum to use raw values:
enum WeekDay: Int {
case Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
func printCurrentDay(day: WeekDay) {
switch day {
case .Monday:
print("Today is Monday")
// ... repeat for the other days
default:
print("Invalid day")
}
}In this example, each case now includes a raw value. We've also defined the raw values for Monday and the rest of the days manually. The raw value for Tuesday, Wednesday, etc., will be automatically assigned starting from the value of the last manually defined raw value (1 in this case) plus one.
What is the benefit of using associated values in Enum cases?