Swift Switch Pattern Matching With Booleans & Optionals

Pattern Matching For Bool values

let isError = false
let isWarning = true
let isFlawless = true

switch true {
case isError:
    print("Oooh! There is an error")
case isWarning:
    print("Oooh! There is a warning")
case isFlawless:
    print("Everything good")
default:
    break
}
let email: String? = "someone@example.com"
let password: String? = nil

let isEmailProvided = email != nil
let isPasswordProvided = password != nil

switch false {
case isEmailProvided:
    print("Provide an email")
case isPasswordProvided:
    print("Provide a password")
default:
    print("All good! We can proceed")
}

Pattern Matching For nil

With Optional type, switch has a use case for nil checking. Opposite to writing a lot of if/guard statements for each check.

let email: Optional<String> = "someone@example.com"
let password: Optional<String> = nil

switch Optional<String>.none {
case email:
    print("Provide an email")
case password:
    print("Provide a password")
default:
    print("All good! We can proceed")
}

Same as

let email: String? = "someone@example.com"
let password: String? = nil

switch Optional<String>.none {
case email:
    print("Provide an email")
case password:
    print("Provide a password")
default:
    print("All good! We can proceed")
}