Search
Filters
Blog options
Close

Create your own state machine with Swift's versatile Enum type

Create your own state machine with Swift's versatile Enum type

In the past few projects I've been working on I've found myself employing a handy little states machine that I wanted to share with you. Put simply, a states machine is a mechanism that can be in one of a finite number of possible states. The state machine allows us to traverse the possible states in sequential order.

In the following example I've created a states machine that allows the user to switch between different music genres:


enum GenreMachine {
    case Rock
    case Electronic
    case Classic
    
    mutating func next() {
        switch self {
        case Rock: self  = Electronic
        case Electronic: self  = Classic
        case Classic: self  = Rock
        }
    }
// add a previous function! }

So we have defined three different cases for our genres and added a mutating function named next which checks the current state and sets it to the next state in our enum.

So why use the mutating keyword? Enums are value-types in Swift, meaning that they are immutable by default. So, in order for us to change the value of the current instance, we need to allow for mutation, thus the mutating keyword.

Within our mutating next function, we have a switch that switches the current instance based on what its current state is. For instance, if the current state is "Rock", we switch to "Electronic", if the current state is "Classic", we switch to "Rock", you get the picture.

If you download the project files for this article you can see this states machine in action.