Created
December 4, 2024 12:42
-
-
Save lucianoschillagi/41d1ee2bc0eea82b096cd1a3d7eac30e to your computer and use it in GitHub Desktop.
Enums with mutating methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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