11 Protocols and Delegates

WHAT YOU WILL LEARN IN THIS CHAPTER:                  

  • What a protocol is
  • How to define and use a protocol
  • How to conform to a protocol
  • How to declare optional methods in a protocol
  • How to conform to multiple protocols
  • How to specify property requirements in a protocol
  • How to specify initializer requirements in a protocol
  • What a delegate is
  • How to create and use a delegate
  • How protocols and delegates are used in real-life apps

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

The code downloads for this chapter are found at www.wrox.com/go/beginningswift on the Download Code tab.

The use of protocols and delegates reflects one of the most important design patterns in Swift programming. In Chapters 8 and 9 you have seen how classes and inheritance work; and in this chapter, you will learn both how to use protocols to enforce the content of a class and how delegates help to create events and event handlers.

UNDERSTANDING PROTOCOLS

A protocol is a blueprint of methods and properties. It describes what a class should have, and 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.

Defining and Using a Protocol

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

	protocol ProtocolName { func method1() ...

Get Beginning Swift Programming 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.