Methods in protocols

In the Vehicle protocol above, you define a pair of methods, accelerate() and

stop(), that all types conforming to Vehicle must implement.

You define methods on protocols much like you would on any class, struct or enum with parameters and return values:

enum Direction { case left case right

}

protocol DirectionalVehicle { func accelerate()

func stop()

func turn(direction: Direction) func description() -> String

}

There are a few differences to note. You don’t, and in fact cannot, define any implementation for the methods. This is to help you enforce a strict separation of interface and code, as the protocol by itself makes no assumption about the implementation details of any type that conforms to the protocol.

Also, methods defined in protocols can’t contain default parameters:

protocol OptionalDirectionVehicle {

// Build error!

func turn(direction: Direction = .left)

}

To provide direction as an optional argument, you’d define both versions of the method explicitly:

protocol OptionalDirectionVehicle { func turn()

func turn(direction: Direction)

}

You would then define both versions of turn() in any conforming type.

results matching ""

    No results matching ""