-
Book Overview & Buying
-
Table Of Contents
Mastering Swift 6 - Seventh Edition
By :
Pattern matching is a powerful feature in Swift that enables us to compare values against a set of patterns and execute corresponding code blocks. As we saw in the previous example, pattern matching is very well suited for working with enumerations. As another example of pattern matching, let’s create a new enumeration:
enum Weather {
case sunny
case cloudy
case rainy(Int)
case snowy(amount: Int)
}
This example shows how truly flexible associated values can be with enumerations. In this example, we create a weather enumeration with four cases; however, only two of the cases have associated values, and the snowy case has a named associated type. Now, let’s see how we can use the switch statement to match the different cases by creating a showWeather() function:
func showWeather(_ weather: Weather) {
switch weather {
case .sunny:
print("It's sunny")
case .cloudy:
print("It&apos...