In this section, we will look at how to define a protocol, define requirements within a protocol, and specify that a type conforms to a protocol.
The syntax we use to define a protocol is very similar to the syntax used to define a class, structure, or enumeration. The following example shows the syntax used to define a protocol:
protocol MyProtocol { //protocol definition here }
To define the protocol, we use the protocol
keyword followed by the name of the protocol. We then put the requirements, which our protocol defines, between curly brackets. Custom types can state that they conform to a particular protocol by placing the name of the protocol after the type's name, separated by a colon. The following example shows how we would state that the MyStruct
structure conforms to the MyProtocol
protocol:
struct MyStruct: MyProtocol { //structure implementation here }
A type can also conform to multiple protocols. We list...