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

Switching on multiple values

Published on 14 Aug 2019

Switch statements are so incredibly powerful in Swift — especially when used with multiple values and pattern matching. Since cases are evaluated from top to bottom, by putting more specific cases on top, we can create a chain of rules to be evaluated.

func player(_ player: Player,
            didCollideWith object: GameObject) {
    switch (player.state, object.kind) {
    case (.invincible, _):
        object.destroy()
    case (.damaged, .enemy):
        gameOver()
    case (_, .enemy):
        player.takeDamage()
    case (_, .obstacle):
        player.stopMoving()
    }
}

Support Swift by Sundell by checking out this sponsor:

Raycast

Raycast: Take the macOS Spotlight experience to the next level: Create Jira issues, manage GitHub pull requests and control other tools with a few keystrokes. Easily automate every-day tasks and boost your developer productivity by downloading Raycast for free.