Protocols in Collections
Protocols can be used as types, so it shouldn’t be a surprise that a protocol can also be used as the type of a collection. Think about the case of the Walkable
class from the previous section. Say that you want to create something else that can walk, such as a dog. Here’s what you do:
class Dog:Walkable { var name = "Penny" func walk(#numOfSteps:Int) { println("The dog is walking \(numOfSteps) steps") }}let dog = Dog()let human = Human()var walkers = [Walkable]()walkers.append(dog)walkers.append(human)for walker in walkers { walker.walk(numOfSteps:10)}
Here you have a Dog
and a Human
, and they are both Walkable
. You also have an array that is strictly typed for anything ...
Get Learning Swift™ Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.