Enums in Scheme

Enumerated Types in Swift

Enumerated types (enums) are a special case of sum types. An enum is a type that has a fixed number of possible values, each with a distinct name. In Swift, enums are a distinct language feature and are very simple to implement.

Our enum type ServerState is defined as follows:

enum ServerState {
    case idle
    case connected
    case error
    case retrying
}

The possible values for ServerState are defined as cases within the enum.

By implementing the CustomStringConvertible protocol, values of ServerState can be printed out or converted to strings.

extension ServerState: CustomStringConvertible {
    var description: String {
        switch self {
        case .idle:
            return "idle"
        case .connected:
            return "connected"
        case .error:
            return "error"
        case .retrying:
            return "retrying"
        }
    }
}

If we have a value of type Int, we cannot pass it to transition - the compiler will complain about type mismatch. This provides some degree of compile-time type safety for enums.

func main() {
    let ns = transition(.idle)
    print(ns)
    
    let ns2 = transition(ns)
    print(ns2)
}

transition emulates a state transition for a server; it takes the existing state and returns a new state.

func transition(_ s: ServerState) -> ServerState {
    switch s {
    case .idle:
        return .connected
    case .connected, .retrying:
        // Suppose we check some predicates here to determine the next state…
        return .idle
    case .error:
        return .error
    }
}

To run the program, you can put the code in a Swift file and use swift to execute it.

$ swift enums.swift
connected
idle

Now that we can run and build basic Swift programs, let’s learn more about the language.