Introducing protocols

You define a protocol much as you do any other named type. Enter the following into the playground:

protocol Vehicle { func accelerate() func stop()

}

The keyword protocol is followed by the name of the protocol, followed by the curly braces with the members of the protocol inside. The big difference you’ll notice is that the protocol doesn’t contain any implementation.

That means you can’t instantiate a Vehicle directly:

Instead, you use protocols to enforce methods and properties on other types. What you’ve defined here is something like the idea of a vehicle — it’s something that can accelerate and stop.

results matching ""

    No results matching ""