Swift Enum Case Patterns 🎯

beginner
24 min

Swift Enum Case Patterns 🎯

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.

What are Enums? 📝

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.

swift
enum Weekday { case monday, tuesday, wednesday, thursday, friday, saturday, sunday }

In the above example, Weekday is an Enum with seven cases.

What are Case Patterns? 💡

Case patterns in Swift allow you to match an Enum case against a constant and perform specific actions based on the matched case.

swift
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.

Advantages of Case Patterns 📝

  1. Improved Code Organization: Case patterns help keep related code together, making your code more readable and easier to maintain.
  2. Type Safety: Since each case in an Enum is a unique value, it provides type safety, ensuring that only valid cases can be used.
  3. Pattern Matching: You can perform pattern matching with enums, which allows you to write more concise and expressive code.

Raw Values and Associated Values 📝

Swift also allows you to assign raw values and associated values to Enum cases.

Raw Values

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.

swift
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

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.

swift
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.

Quiz 🎯

Quick Quiz
Question 1 of 1

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! 🚀