Chapter 8. Protocols and Extensions: A Swift Lesson in Protocol

Note

You will also extend your knowledge! Get it? No? You will soon.

image

You know all about classes and inheritance, but Swift has a few more tricks for structuring programs, and they’re a lot Swiftier. Meet protocols and extensions. Protocols in Swift let you define a blueprint specifying methods and properties that are required for some purpose, or some piece of functionality. A protocol is adopted by a class, structure, or enumeration, and the actual implementation happens there. Types that provide the functionality needed, and adopt a protocol, are referred to as conforming to that protocol. Extensions simple let you add new functionality to existing types.

image

That’s a fabulous question, and we’re glad you asked.

Swift has a whole other way of building related logic and objects, using protocols and extensions. It’s very Swifty, and it’s kind of unique.

Protocols let you define a set of functionality that something can conform to, without having to provide the implementation until you conform something to it.

A protocol is kind of like a contract: if you define a protocol that requires something to have a property called color, storing a String representing a color, then any type that conforms to that protocol absolutely ...

Get Head First Swift now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.