Bird
Raised Fist0
Swiftprogramming~15 mins

Enum methods and computed properties in Swift - Deep Dive

Choose your learning style10 modes available
Overview - Enum methods and computed properties
What is it?
Enums in Swift are types that group related values together. Enum methods are functions defined inside an enum to add behavior. Computed properties are special properties that calculate a value each time you access them instead of storing it. Together, they let enums do more than just hold values—they can also perform actions and provide dynamic information.
Why it matters
Without methods and computed properties, enums would only hold fixed values, limiting their usefulness. Adding these features lets you attach behavior and logic directly to enum cases, making your code cleaner and easier to understand. This helps you write safer and more organized programs, especially when handling different states or options.
Where it fits
Before learning this, you should understand basic Swift enums and properties. After this, you can explore advanced enum features like associated values, raw values, and protocol conformance. This knowledge also prepares you for designing complex data models and state machines.
Mental Model
Core Idea
Enums with methods and computed properties are like labeled boxes that not only store values but also know how to act and provide extra information about themselves.
Think of it like...
Imagine a vending machine with buttons (enum cases). Each button not only represents a snack but also knows its price (computed property) and can tell you if it's available (method). The buttons are simple, but with these extra features, they become smart helpers.
Enum Example
╔════════════════════════════╗
║        Enum: Snack         ║
╠════════════════════════════╣
║ Cases:                    ║
║  - chips                 ║
║  - chocolate             ║
║  - soda                  ║
╠════════════════════════════╣
║ Computed Property: price  ║
║ Method: isAvailable()     ║
╚════════════════════════════╝
Build-Up - 7 Steps
1
FoundationBasic enum declaration in Swift
🤔
Concept: Learn how to define a simple enum with cases.
enum Direction { case north case south case east case west } // This enum groups four directions as named cases.
Result
You have a type Direction with four possible values: north, south, east, and west.
Understanding how to declare enums is the foundation for adding behavior like methods and computed properties.
2
FoundationIntroduction to computed properties
🤔
Concept: Learn what computed properties are and how to add them to types.
struct Rectangle { var width: Double var height: Double var area: Double { return width * height } } // area is a computed property that calculates the rectangle's area each time it's accessed.
Result
Accessing rectangle.area returns the product of width and height dynamically.
Computed properties let you create values that update automatically based on other data, without storing extra memory.
3
IntermediateAdding methods to enums
🤔Before reading on: do you think enums can have functions that perform actions? Commit to yes or no.
Concept: Enums can have methods to add behavior related to their cases.
enum Direction { case north, south, east, west func description() -> String { switch self { case .north: return "Up" case .south: return "Down" case .east: return "Right" case .west: return "Left" } } } let dir = Direction.north print(dir.description()) // Output: Up
Result
Calling description() on an enum case returns a string describing it.
Knowing enums can have methods helps you bundle related logic directly with the enum, improving code clarity.
4
IntermediateComputed properties inside enums
🤔Before reading on: do you think computed properties in enums can use switch statements? Commit to yes or no.
Concept: Enums can have computed properties that return values based on the current case.
enum Snack { case chips, chocolate, soda var price: Double { switch self { case .chips: return 1.5 case .chocolate: return 2.0 case .soda: return 1.0 } } } let snack = Snack.chocolate print(snack.price) // Output: 2.0
Result
Accessing snack.price returns the price for the specific snack case.
Computed properties in enums let you provide dynamic information tied to each case without extra storage.
5
IntermediateUsing methods and computed properties together
🤔Before reading on: can methods and computed properties in enums interact? Commit to yes or no.
Concept: Methods and computed properties can work together inside enums to provide rich behavior.
enum TrafficLight { case red, yellow, green var action: String { switch self { case .red: return "Stop" case .yellow: return "Caution" case .green: return "Go" } } func canGo() -> Bool { return self == .green } } let light = TrafficLight.yellow print(light.action) // Output: Caution print(light.canGo()) // Output: false
Result
You get both a descriptive string and a boolean decision from the enum instance.
Combining methods and computed properties lets enums represent both data and logic cleanly.
6
AdvancedMutating methods in enums
🤔Before reading on: do you think enum methods can change the enum’s own case? Commit to yes or no.
Concept: Enums can have mutating methods that change their own case when called on a variable instance.
enum Switch { case on, off mutating func toggle() { switch self { case .on: self = .off case .off: self = .on } } } var lightSwitch = Switch.off lightSwitch.toggle() print(lightSwitch) // Output: off
Result
Calling toggle() changes the enum case from off to on.
Understanding mutating methods in enums unlocks state changes directly inside enum instances.
7
ExpertComputed properties with associated values
🤔Before reading on: can computed properties access associated values inside enum cases? Commit to yes or no.
Concept: Computed properties can extract and use associated values from enum cases to compute results dynamically.
enum Measurement { case weight(Double) case height(Double) var description: String { switch self { case .weight(let kg): return "Weight is \(kg) kg" case .height(let cm): return "Height is \(cm) cm" } } } let measure = Measurement.weight(70) print(measure.description) // Output: Weight is 70.0 kg
Result
The computed property returns a string using the associated value inside the enum case.
Knowing computed properties can access associated values lets you build flexible, descriptive enums that carry data and behavior.
Under the Hood
Swift enums are implemented as a type with a fixed set of possible values. When you add methods or computed properties, the compiler generates functions tied to the enum type. Computed properties run code each time you access them, often using switch statements to check the current case. Mutating methods can change the enum's stored case because enums are value types, and marking methods as mutating allows modification of self.
Why designed this way?
Swift was designed to make enums more powerful and expressive than simple lists of values. Adding methods and computed properties lets enums encapsulate both data and behavior, following modern programming principles. This design avoids the need for separate helper functions and keeps related logic close to the data it operates on, improving safety and readability.
Enum with Methods and Computed Properties
╔════════════════════════════════════╗
║ Enum Type: TrafficLight            ║
╠════════════════════════════════════╣
║ Cases: red, yellow, green          ║
║                                    ║
║ Computed Property: action          ║
║   └─ runs switch on self           ║
║   └─ returns String                ║
║                                    ║
║ Method: canGo()                    ║
║   └─ checks if self == .green     ║
║   └─ returns Bool                  ║
╚════════════════════════════════════╝
Myth Busters - 4 Common Misconceptions
Quick: Can enum computed properties store values like regular properties? Commit to yes or no.
Common Belief:Computed properties in enums store values just like regular stored properties.
Tap to reveal reality
Reality:Computed properties do not store values; they calculate and return a value each time they are accessed.
Why it matters:Assuming computed properties store values can lead to unexpected behavior and bugs when the value depends on other data or changes over time.
Quick: Can enum methods modify the enum case without being marked mutating? Commit to yes or no.
Common Belief:Enum methods can change the enum’s case freely without special keywords.
Tap to reveal reality
Reality:Only methods marked as mutating can change the enum’s case because enums are value types.
Why it matters:Not marking methods as mutating when they modify self causes compiler errors and confusion about how enums behave.
Quick: Do all enum cases share the same computed property value? Commit to yes or no.
Common Belief:Computed properties return the same value regardless of the enum case.
Tap to reveal reality
Reality:Computed properties usually return different values depending on the current enum case, often using switch statements.
Why it matters:Thinking computed properties are static can cause misuse and limit the power of enums to represent varied data.
Quick: Can computed properties in enums access associated values? Commit to yes or no.
Common Belief:Computed properties cannot use associated values inside enum cases.
Tap to reveal reality
Reality:Computed properties can access and use associated values via pattern matching in switch statements.
Why it matters:Missing this limits the ability to write expressive enums that combine data and behavior.
Expert Zone
1
Computed properties in enums are recomputed every time they are accessed, so avoid expensive calculations inside them without caching.
2
Mutating methods on enums change the entire enum value, not just parts, because enums are value types, which can affect performance if used heavily.
3
Enums with methods and computed properties can conform to protocols, enabling polymorphism and more flexible designs.
When NOT to use
Avoid adding complex logic or heavy computations inside enum computed properties or methods if performance is critical; consider using structs or classes instead. Also, if you need mutable state beyond changing the enum case, enums may not be the best choice.
Production Patterns
In real-world Swift apps, enums with methods and computed properties are used to model state machines, represent API response types with behavior, and encapsulate UI states with descriptive logic. For example, an enum representing app themes might have computed properties for colors and methods to apply styles.
Connections
Object-Oriented Programming (OOP) Methods
Enums with methods are similar to classes having functions that operate on their data.
Understanding enum methods helps bridge the gap between simple data containers and full objects with behavior, showing how Swift blends functional and OOP styles.
Functional Programming Pattern Matching
Computed properties in enums often use switch statements, a form of pattern matching common in functional languages.
Recognizing this connection helps learners appreciate how Swift enums combine functional patterns with imperative code.
State Machines in Systems Engineering
Enums with methods and computed properties model states and transitions, like state machines used in engineering.
Seeing enums as state machines clarifies their role in managing complex workflows and system states in software.
Common Pitfalls
#1Trying to store a value in a computed property inside an enum.
Wrong approach:enum Example { var storedValue: Int = 5 // Error: Computed properties cannot store values }
Correct approach:enum Example { var computedValue: Int { return 5 } }
Root cause:Confusing computed properties with stored properties; computed properties only calculate and return values.
#2Modifying enum case inside a method without marking it mutating.
Wrong approach:enum Light { case on, off func toggle() { self = (self == .on) ? .off : .on // Error: Cannot assign to self in non-mutating method } }
Correct approach:enum Light { case on, off mutating func toggle() { self = (self == .on) ? .off : .on } }
Root cause:Not understanding that value types require mutating keyword to change self inside methods.
#3Assuming computed properties return the same value for all enum cases.
Wrong approach:enum Color { case red, green, blue var hex: String { return "#FFFFFF" // Incorrect: same value for all cases } }
Correct approach:enum Color { case red, green, blue var hex: String { switch self { case .red: return "#FF0000" case .green: return "#00FF00" case .blue: return "#0000FF" } } }
Root cause:Not using switch or pattern matching to differentiate behavior per enum case.
Key Takeaways
Swift enums can have methods and computed properties that add behavior and dynamic information to each case.
Computed properties calculate values on demand and do not store data, making enums more flexible and expressive.
Mutating methods allow enums to change their own case, enabling state changes within value types.
Using switch statements inside methods and computed properties lets you customize behavior for each enum case.
Combining these features helps you write safer, clearer, and more organized code by bundling data and logic together.

Practice

(1/5)
1. What is the purpose of adding methods to an enum in Swift?
easy
A. To inherit properties from other enums
B. To store additional data inside enum cases
C. To perform actions or calculations related to enum cases
D. To convert enums into classes automatically

Solution

  1. Step 1: Understand enum methods

    Enum methods allow you to add functions that perform tasks related to the enum's cases.
  2. Step 2: Differentiate from other enum features

    Enums do not store extra data like classes; methods help organize related actions.
  3. Final Answer:

    To perform actions or calculations related to enum cases -> Option C
  4. Quick Check:

    Enum methods = perform actions [OK]
Hint: Methods in enums perform actions tied to cases [OK]
Common Mistakes:
  • Thinking enums can inherit from other enums
  • Confusing methods with stored properties
  • Assuming enums convert to classes automatically
2. Which of the following is the correct syntax to declare a computed property inside an enum in Swift?
easy
A. static var description: String = "Example"
B. func description() -> String { return "Example" }
C. let description = "Example"
D. var description: String { return "Example" }

Solution

  1. Step 1: Identify computed property syntax

    Computed properties use var with a code block returning a value, like var name: Type { ... }.
  2. Step 2: Check options

    var description: String { return "Example" } matches computed property syntax; B is a method, C is a stored property, D is a static stored property.
  3. Final Answer:

    var description: String { return "Example" } -> Option D
  4. Quick Check:

    Computed property syntax = var with braces [OK]
Hint: Computed properties use var with braces returning a value [OK]
Common Mistakes:
  • Using func instead of var for computed properties
  • Declaring computed properties as let constants
  • Confusing static stored properties with computed ones
3. Consider this Swift enum with a computed property and method:
enum Direction {
    case north, south, east, west

    var isVertical: Bool {
        return self == .north || self == .south
    }

    func description() -> String {
        switch self {
        case .north: return "Up"
        case .south: return "Down"
        case .east: return "Right"
        case .west: return "Left"
        }
    }
}

let dir = Direction.east
print(dir.isVertical)
print(dir.description())

What is the output?
medium
A. false Right
B. true Right
C. false East
D. true East

Solution

  1. Step 1: Evaluate computed property isVertical

    For Direction.east, isVertical checks if east == north or south, which is false.
  2. Step 2: Evaluate description() method

    Switch on east returns "Right" string.
  3. Final Answer:

    false Right -> Option A
  4. Quick Check:

    east isVertical = false, description = Right [OK]
Hint: Check enum case matches in computed property and switch [OK]
Common Mistakes:
  • Assuming east is vertical
  • Confusing method return values with case names
  • Forgetting to call method with parentheses
4. This Swift enum code has an error:
enum Status {
    case success, failure

    var message: String {
        switch self {
        case .success:
            return "Success"
        case .failure
            return "Failure"
        }
    }
}

What is the error and how to fix it?
medium
A. Computed property must be a function; change to func message() -> String
B. Missing colon after case .failure; add ':' after .failure
C. Enum cases must have raw values; add raw values to cases
D. Return statements are not allowed in computed properties; remove returns

Solution

  1. Step 1: Identify syntax error in switch cases

    Case .failure is missing a colon ':' after it, causing a syntax error.
  2. Step 2: Fix the syntax

    Add ':' after case .failure to correct the switch syntax.
  3. Final Answer:

    Missing colon after case .failure; add ':' after .failure -> Option B
  4. Quick Check:

    Switch case syntax requires ':' [OK]
Hint: Switch cases must end with a colon ':' [OK]
Common Mistakes:
  • Thinking computed properties need func keyword
  • Adding raw values unnecessarily
  • Removing return statements inside computed properties
5. You want to create an enum Light with cases red, yellow, and green. Add a computed property time that returns the duration in seconds for each light: red = 30, yellow = 5, green = 25. Also add a method next() that returns the next light in the traffic cycle (red -> green -> yellow -> red). Which implementation is correct?
hard
A. enum Light { case red, yellow, green var time: Int { switch self { case .red: return 30 case .yellow: return 5 case .green: return 25 } } func next() -> Light { switch self { case .red: return .green case .green: return .yellow case .yellow: return .red } } }
B. enum Light { case red, yellow, green func time() -> Int { if self == .red { return 30 } else if self == .yellow { return 5 } else { return 25 } } func next() -> Light { if self == .red { return .yellow } else if self == .yellow { return .green } else { return .red } } }
C. enum Light { case red, yellow, green var time: Int { if self == .red { return 30 } else if self == .yellow { return 5 } else { return 25 } } func next() -> Light { switch self { case .red: return .yellow case .yellow: return .green case .green: return .red } } }
D. enum Light { case red, yellow, green var time: Int { switch self { case .red: return 25 case .yellow: return 30 case .green: return 5 } } func next() -> Light { switch self { case .red: return .green case .green: return .yellow case .yellow: return .red } } }

Solution

  1. Step 1: Check computed property time values

    enum Light { case red, yellow, green var time: Int { switch self { case .red: return 30 case .yellow: return 5 case .green: return 25 } } func next() -> Light { switch self { case .red: return .green case .green: return .yellow case .yellow: return .red } } } correctly returns 30 for red, 5 for yellow, and 25 for green as required.
  2. Step 2: Check next() method cycle order

    enum Light { case red, yellow, green var time: Int { switch self { case .red: return 30 case .yellow: return 5 case .green: return 25 } } func next() -> Light { switch self { case .red: return .green case .green: return .yellow case .yellow: return .red } } } cycles red -> green -> yellow -> red, matching the problem statement.
  3. Final Answer:

    enum Light { case red, yellow, green var time: Int { switch self { case .red: return 30 case .yellow: return 5 case .green: return 25 } } func next() -> Light { switch self { case .red: return .green case .green: return .yellow case .yellow: return .red } } } -> Option A
  4. Quick Check:

    Correct time values and cycle order = enum Light { case red, yellow, green var time: Int { switch self { case .red: return 30 case .yellow: return 5 case .green: return 25 } } func next() -> Light { switch self { case .red: return .green case .green: return .yellow case .yellow: return .red } } } [OK]
Hint: Match switch cases exactly to problem requirements [OK]
Common Mistakes:
  • Mixing up time values for colors
  • Incorrect next() cycle order
  • Using func instead of computed property for time
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard