Welcome to our comprehensive guide on Swift Enum Case Patterns! In this lesson, we'll dive deep into understanding how enums and their associated case patterns work in Swift, making your code more organized and expressive.
An Enum (Enumeration) in Swift is a custom data type that represents a set of related values. These values, called cases, are used to represent a limited set of possibilities.
enum Weekday {
case monday, tuesday, wednesday, thursday, friday, saturday, sunday
}In the above example, Weekday is an Enum with seven cases.
Case patterns in Swift allow you to match an Enum case against a constant and perform specific actions based on the matched case.
func greet(day: Weekday) {
switch day {
case .monday:
print("Hello, it's Monday!")
case .tuesday:
print("Hello, it's Tuesday!")
// ... and so on
}
}In the above example, the greet function takes a Weekday Enum and uses a switch statement to match the day with the Enum cases.
Swift also allows you to assign raw values and associated values to Enum cases.
Raw values are simple values (like integers, strings, or even other enums) assigned to Enum cases. They are used to provide a unique identifier for each case.
enum Weekday: Int {
case monday = 1, tuesday, wednesday, thursday, friday, saturday, sunday
}In the above example, each Weekday case has an associated integer raw value.
Associated values allow you to add additional data to each case. They are useful when you want to store more complex data with each Enum case.
enum Car {
case sedan(brand: String, year: Int)
case suv(brand: String, year: Int, numOfDoors: Int)
}In the above example, each Car case has an associated data structure containing the brand, year, and number of doors.
What is the purpose of Case Patterns in Swift?
Stay tuned for our next lesson, where we'll delve deeper into pattern matching and how to create custom operators for enums! 🚀