Challenge C: Pattern matching enumeration values
Taking the map example from earlier in the chapter, begin with the Direction
enumeration:
enum Direction { case north case south case east case west
}
Imagine starting a new level in a video game. The character makes a series of movements in the game. Calculate the position of the character on a top-down level map:
let movements: [Direction] = [.north, .north, .west, .south,
.west, .south, .south, .east, .east, .south, .east]
Hint: Use a tuple for the location:
var location = (x: 0, y: 0)
In this book, you’ve learned about the core types the Swift language provides, including user-defined named types. There’s one final type that can bridge common behaviors between structs, classes and enums. In fact, it is itself a user-defined named type: the protocol.
However, protocols don’t define a type you can instantiate directly. Instead, they define an interface or a template for an actual concrete type such as a struct, class or enumeration. With a protocol, you can define a common set of behaviors and then define the actual types that implement them.
In this chapter, you’ll learn about protocols and see why they’re central to programming in Swift.