Protocols as Types

You know that protocols don’t implement any functionality themselves, but that doesn’t stop you from using them as parameters or return types in methods. This is where protocols can become extremely powerful. You can use them as a type for a variable or constant, or for arrays and dictionaries.

Here is a protocol that can work for anything that you would like to make walkable:

protocol Walkable {    var name:String { get set }    func walk(#numOfSteps:Int)}

Humans can walk and animals can walk, among other actions. Here’s how you can make a human that can walk:

class Human:Walkable {    var name = "John"    func walk(#numOfSteps:Int) {        println("Human is walking ...

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.