Implementing protocols

Now that you know how to define a protocol, you’ll next learn how to implement them.

As you’ve already seen, when you declare your type as conforming to a protocol, you must implement all the requirements declared in the protocol:

protocol Vehicle { func accelerate() func stop()

}

class Bike: Vehicle { var peddling = false

var brakesApplied = false

func accelerate() { peddling = true brakesApplied = false

}

func stop() { peddling = false

brakesApplied = true

}

}

The class Bike implements all the methods defined in Vehicle. If accelerate() or

stop() weren’t defined, you’d receive a build error.

Defining a protocol guarantees any type that conforms to the protocol will have all

the members you’ve defined in the protocol.

results matching ""

    No results matching ""