Methods in Enums
Enums can have their own actions too, just like structs and classes, letting each option know how to behave.
Syntax
enum EnumName {
case first, second
func methodName() -> ReturnType {
switch self {
case .first: return value
case .second: return value
}
}
mutating func change() { self = .second }
}
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
// Define an enum `TrafficLight` listing its possible cases
enum TrafficLight {
// Enum case(s): `red, yellow, green`
case red, yellow, green
// Define the function `instruction` with no parameters and returning a String
func instruction() -> String {
// Switch on `self` and branch by case
switch self {
case .red: return "Stop"
case .yellow: return "Slow down"
case .green: return "Go"
}
}
}
// Declare a constant `light`, set to `TrafficLight.green`
let light = TrafficLight.green
// Print `light.instruction()` to the console
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
// Define an enum `TrafficLight` listing its possible cases
enum TrafficLight {
// Enum case(s): `red, yellow, green`
case red, yellow, green
mutating func next() {
// Switch on `self` and branch by case
switch self {
// Enum case(s): `.red: self = .green`
case .red: self = .green
// Enum case(s): `.green: self = .yellow`
case .green: self = .yellow
// Enum case(s): `.yellow: self = .red`
case .yellow: self = .red
}
}
}
// Declare a mutable variable `light`, initialized to `TrafficLight.red`
var light = TrafficLight.red
light.next()
// Print `light` to the console
print(light)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: