O'Reilly logo

Swift Quick Syntax Reference by Matthew Campbell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required