Skip to content

Instantly share code, notes, and snippets.

@lucianoschillagi
Created December 4, 2024 12:42
Show Gist options
  • Select an option

  • Save lucianoschillagi/41d1ee2bc0eea82b096cd1a3d7eac30e to your computer and use it in GitHub Desktop.

Select an option

Save lucianoschillagi/41d1ee2bc0eea82b096cd1a3d7eac30e to your computer and use it in GitHub Desktop.
Enums with mutating methods
import Foundation
enum TrafficLight {
case red, yellow, green // TrafficLight cases
mutating func next() {
switch self { // self = TrafficLight
case .red:
self = .green
case .green:
self = .yellow
case .yellow:
self = .red
}
}
}
var currentLight = TrafficLight.red
currentLight.next() // to green
print(currentLight)
currentLight.next() // to yellow
print(currentLight)
currentLight.next() // to red
print(currentLight)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment