Bird
Raised Fist0
Swiftprogramming~10 mins

Enum methods and computed properties in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Enum methods and computed properties
Define Enum with cases
↓
Add computed property
↓
Add method
↓
Create enum instance
↓
Access computed property
↓
Call method
↓
Use returned values
This flow shows how to define an enum with computed properties and methods, then create instances and use those features.
Execution Sample
Swift
enum Direction {
    case north, south, east, west

    var description: String {
        switch self {
        case .north: return "Up"
        case .south: return "Down"
        case .east: return "Right"
        case .west: return "Left"
        }
    }

    func opposite() -> Direction {
        switch self {
        case .north: return .south
        case .south: return .north
        case .east: return .west
        case .west: return .east
        }
    }
}

let dir = Direction.north
print(dir.description)
print(dir.opposite())
Defines an enum Direction with a computed property description and a method opposite, then prints values for north.
Execution Table
StepActionEnum InstanceComputed Property AccessMethod CallOutput
1Create enum instancenorth---
2Access computed property 'description'northUp-Up
3Call method 'opposite()'north-southsouth
4Print description---Up
5Print opposite---south
6End of program----
💡 Program ends after printing description and opposite direction.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
dirnilnorthnorthnorthnorth
Key Moments - 3 Insights
Why does accessing 'description' not require parentheses?
Because 'description' is a computed property, not a method, so you access it like a variable (see execution_table step 2).
Why do we use 'self' inside the computed property and method?
'self' refers to the current enum instance, allowing the switch to choose the right case (see code in execution_sample).
What is returned by the method 'opposite()' when called on 'north'?
It returns the enum case 'south', the opposite direction (see execution_table step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output when accessing 'description' for 'dir' at step 2?
A"north"
B"Up"
C"Down"
D"south"
💡 Hint
Check the 'Computed Property Access' and 'Output' columns at step 2 in the execution_table.
At which step does the method 'opposite()' return 'south'?
AStep 3
BStep 2
CStep 4
DStep 5
💡 Hint
Look at the 'Method Call' column in execution_table for the returned value.
If we change 'dir' to '.east', what would 'dir.opposite()' return?
A.south
B.north
C.west
D.east
💡 Hint
Refer to the method 'opposite()' switch cases in the code sample.
Concept Snapshot
enum Direction {
  case north, south, east, west

  var description: String { // computed property
    switch self {
    case .north: return "Up"
    ...
    }
  }

  func opposite() -> Direction { // method
    switch self {
    case .north: return .south
    ...
    }
  }
}

Use computed properties like variables, methods with parentheses.
Full Transcript
This example shows how to add computed properties and methods to a Swift enum. We define an enum Direction with four cases. The computed property 'description' returns a string for each case using a switch on self. The method 'opposite()' returns the opposite direction. We create an instance 'dir' set to north. Accessing 'dir.description' returns "Up". Calling 'dir.opposite()' returns the enum case south. Computed properties are accessed without parentheses, methods require parentheses. The 'self' keyword refers to the current enum case inside the property and method. This helps organize related data and behavior inside enums clearly.

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