#49: Pattern Matching with guard case in Swift
guard case is the early-exit sibling of if case. It is great when the rest of the function only makes sense for one specific pattern.
enum APIResponse {
case success(Data)
case failure(Int)
}
func handle(_ response: APIResponse) {
guard case let .success(data) = response else {
return
}
print(data.count)
}
This keeps the happy path unindented and makes the intent clear: continue only if the value matches the pattern.
You can also combine it with extra conditions, which makes it handy for compact validation code.