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

Matching multiple enum cases with associated values

Published on 12 Sep 2018

Swift's pattern matching capabilities are so powerful! Two enum cases with associated values can even be matched and handled by the same switch case - which is super useful when handling state changes with similar data.

enum DownloadState {
    case inProgress(progress: Double)
    case paused(progress: Double)
    case cancelled
    case finished(Data)
}

func downloadStateDidChange(to state: DownloadState) {
    switch state {
    case .inProgress(let progress), .paused(let progress):
        updateProgressView(with: progress)
    case .cancelled:
        showCancelledMessage()
    case .finished(let data):
        process(data)
    }
}

Support Swift by Sundell by checking out this sponsor:

Essential Developer

Essential Developer: If you’re a mid/senior iOS developer who’s looking to improve both your skills and your salary level, then join the iOS Architect Crash Course, starting on January 31st. It’s 100% free and held entirely online. Click to learn more.