This playground introduces the concept of pattern matching. A pattern is a way to describe and match a set of values based on certain rules, such as “all tuples whose first value is 0
,” “all numbers in the range 1...5
,” or “all class instances of a certain type.” Patterns in Swift enable you to write conditional statements (such as switch
statements) that match multiple values in a concise and readable way.
Matching Values in a Tuple
Here’s an example of how pattern matching can help you write simple, elegant switch statements. This example is based on the game FizzBuzz. In this game, you count upwards from 1. If you reach a number that divides by 3, you say “Fizz!” instead of the number. If you reach a number that divides by 5, you say “Buzz!” instead of the number. If the number divides by 3 and 5, you say “FizzBuzz!.” So, starting from 1, you say “1, 2, Fizz!, 4, Buzz!,” and so on. Here, the game is expressed as a function called fizzBuzz
that takes a number and returns an appropriate String
value for that number