Chapter    46

Protocols

When you want to specify properties, methods, and types that would require other types to implement, you can use protocols. A protocol can be adopted by a type. Adopting a protocol means that a type will agree to implement the definition defined in the protocol.

To define a protocol, use the protocol keyword (see Listing 46-1).

Listing 46-1. Defining a Protocol

protocol PrinterProtocol {    func printThis()}

In Listing 46-1, you coded a new protocol named PrinterProtocol, which defined a function named printThis(). If you coded a class that you wanted to adopt this protocol, you would write the code shown in Listing 46-2.

Listing 46-2. Adopting a Protocol

class aClass:PrinterProtocol {}

In Listing 46-2, you defined a ...

Get Swift Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.