Swift - What a protocol is

Introduction

A protocol lists methods and properties that a class should have.

It does not provide any implementation.

A class that conforms to a protocol needs to provide the implementation as dictated by the protocol.

A protocol can be implemented by a class, a structure, or an enumeration.

A protocol is similar to Java interface.

Defining and Using a Protocol

To define a protocol, use the protocol keyword, followed by the name of the protocol:

protocol   ProtocolName  {
    func method1 ()
    func method2 ()
     ...
}

Methods in a protocol follow the same syntax as normal methods in a class.

You are not allowed to specify default values for method parameters in protocol.

Here is an example of a protocol:

protocol  Movable {
    func accelerate ()
    func decelerate ()
}

Here, the code declares a protocol named Movable containing two methods: accelerate() and decelerate().

A class that wants to implement a truck that can accelerate or decelerate can conform to this protocol.

Related Topic