Protocol syntax
A protocol can be adopted by a class, struct, or enum — and when another type adopts a protocol, it’s required to implement the methods and properties defined in the protocol. Once a type implements all members of a protocol, the type is said to conform to the protocol.
Here’s how you declare protocol conformance for your type. In the playground, define a new class that will conform to Vehicle:
class Unicycle: Vehicle { var peddling = false
func accelerate() { peddling = true
}
func stop() { peddling = false
}
}
You follow the name of the named type with a semicolon and the name of the protocol you want to conform to. This syntax might look familiar, since it’s the same syntax you use to make a class inherit from another class. In this example, Unicycle conforms to the Vehicle protocol.
Note that it looks like class inheritance but it isn’t; structs and enumerations can also conform to protocols with this syntax.
If you were to remove the definition of stop() from the class Unicycle above, Swift would display an error since Unicycle wouldn’t have fully conformed to the Vehicle protocol.
You’ll come back to the details of implementing protocols in a bit, but first you’ll see what’s possible when defining protocols.