Articles, podcasts and news about Swift development, by John Sundell.

The flexible syntax of enums

Published on 20 Feb 2019
Basics article available: Enums

One of the things I love about Swift enums is how flexible the syntax is — both when defining cases and when handling them in a switch statement (which I always recommend, to ”force” the code to handle all various states).

// There are many different ways to define enum cases in Swift:
enum PlaybackState {
    // With one or many associated values with explicit labels:
    case paused(progress: Percentage)
    case playing(progress: Percentage, playbackSpeed: Double)
    // Without labels:
    case failed(Error)
    // Or without any associated values at all:
    case finished
}

// Regardless, we have a lot of freedom when choosing how to
// handle a case at the call site:
func updatePlaybackPositionView(for state: PlaybackState) {
    switch state {
    // We can handle multiple values, and pick which ones we
    // want to handle, and which we want to ignore:
    case .paused(let progress), .playing(let progress, _):
        view.fillRate = progress
    // Or simply ignore all associated values if they're not
    // relevant for this particular piece of code:
    case .failed, .finished:
        break
    }
}

Support Swift by Sundell by checking out this sponsor:

Essential Developer

Essential Developer: Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for developers who want to become complete senior iOS developers. This virtual event includes lectures, mentoring sessions, and step-by-step instructions. Click to learn more.