Enums in Scheme
On this page
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:
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.
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.
transition
emulates a state transition for a server; it takes the existing state and returns a new state.
To run the program, you can put the code in a Swift file and use swift
to execute it.
Now that we can run and build basic Swift programs, let’s learn more about the language.