Enumeration case pattern

In Chapter 16, “Enumerations” you saw how you could match the member values of an enumeration:

enum Direction {

case north, south, east, west

}

let heading = Direction.north if case .north = heading {

print("Don't forget your jacket") // Printed!

}

As you might imagine, the enumeration case pattern matches the value of an enumeration. In this example, case .north will only match for the .north value of the enumeration.

The enumeration case pattern has some magic up its sleeve. When you combine it with the value binding pattern you can extract associated values from an enumeration:

enum Organism { case plant

case animal(legs: Int)

}

let pet = Organism.animal(legs: 4) switch pet {

case .animal(let legs):

print("Potentially cuddly with (legs) legs") // Printed: 4 default:

print("No chance for cuddles")

}

In this code the associated value for .animal is bound to the constant named legs. You reference the legs constant in the print call inside the execution block of that condition.

Associated values are locked away in enumeration values until you use the value- binding pattern to extract them.

results matching ""

    No results matching ""