This article has been archived, as it was published several years ago, so some of its information might now be outdated. For more recent articles, please visit the main article feed.
Switching on multiple values
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()
}
}

Swift by Sundell is brought to you by the Genius Scan SDK — Add a powerful document scanner to any mobile app, and turn scans into high-quality PDFs with one line of code. Try it today.