#48: Pattern Matching with if case in Swift

Sometimes a full switch is more than you need. If you only care about a single enum case, if case is a compact alternative.

enum DownloadState {
    case idle
    case loading(Double)
    case failed(Error)
}

let state = DownloadState.loading(0.42)

if case let .loading(progress) = state {
    print(progress)
}

This is especially handy when the success path is short and you do not want to add a default branch just to ignore everything else.

The same idea also works with associated values, tuples and wildcards, so it is worth keeping in mind when a full switch would feel too heavy.


I'm also on Twitter and GitHub.

Subscribe via RSS.