Basics ยท SWIFT RECIPE

Model choices with an enum

Name a finite set of states and switch over them.

main.swift
enum Status { case queued, running, finished }
let status = Status.running
switch status {
case .queued: print("Waiting")
case .running: print("Working")
case .finished: print("Done")
}

How it works

An enum models a closed set of cases. An exhaustive switch makes the compiler verify that you handle all of them. Associated values can attach additional data.

EXPECTED OUTPUT
Working

Keep in mind

Avoid default when you want new cases to trigger compile errors at each switch.

Read the Swift language reference