← Back to Swift Course | Chapter 10: Enums | Lesson 5 of 6

Methods in Enums

Enums can have their own actions too, just like structs and classes, letting each option know how to behave.

Defining a Method on an Enum

An enum method can use switch self to produce different behavior depending on which case the instance currently is.

Example: Defining a Method on an Enum

markup
enum TrafficLight {
    case red, yellow, green
    func instruction() -> String {
        switch self {
        case .red: return "Stop"
        case .yellow: return "Slow down"
        case .green: return "Go"
        }
    }
}
let light = TrafficLight.green
print(light.instruction())

A Mutating Method that Changes Cases

A mutating method on an enum can reassign self to a different case entirely, which is how you model state transitions.

Example: A Mutating Method that Changes Cases

markup
enum TrafficLight {
    case red, yellow, green
    mutating func next() {
        switch self {
        case .red: self = .green
        case .green: self = .yellow
        case .yellow: self = .red
        }
    }
}
var light = TrafficLight.red
light.next()
print(light)
Common Mistakes
  1. Forgetting an enum method that needs to change self to a different case must be marked mutating, just like a struct.
  2. Writing a big external switch function to compute behavior per case when a method defined right on the enum, using self in a switch, would be more natural.
  3. Not realizing enums can also have computed properties and static methods, just like structs and classes.
Chapter Summary
  • Enums can define instance methods, just like structs and classes.
  • A method that reassigns self to a different case must be marked mutating.
  • Methods often use switch self internally to vary behavior per case.
  • Enums can also have static methods and computed properties.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.