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:

Essential Developer

Essential Developer: Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for developers who want to become complete senior iOS developers. This virtual event includes lectures, mentoring sessions, and step-by-step instructions. Click to learn more.