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
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())
Login to try C/C++/Java/PHP code in the editor
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
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)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting an enum method that needs to change
selfto a different case must be markedmutating, just like a struct. - Writing a big external
switchfunction to compute behavior per case when a method defined right on the enum, usingselfin a switch, would be more natural. - 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
selfto a different case must be markedmutating. - Methods often use
switch selfinternally 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: