Protocols - Introduction

Swift is swift largely because so many standard types are structs, not classes, and Swift encourages you to create structs wherever possible. Structs don’t have inheritance to support polymorphism — they use protocols, instead. And protocols work just as well with classes, enums and other protocols — you can compose or inherit protocols, providing you with unlimited flexibility in creating a modular app architecture.

It’s hard to see just how useful protocols are until you work on a large codebase and for a long time. Everything protocols offer can be approximated in other ways, using inheritance, generics, function overloading, or copying and pasting code. By using protocols, you get clear intentions and semantics as well as protocol-guaranteed safety and ease of refactoring.

Learning Objectives

You already learned a lot about protocols from Object Oriented Programming in iOS — how to create protocols, how to extend and compose them, how they support SOLID principles, and a bit about protocols with associated types. Here’s what you’ll learn in this lesson:

  • How to decide whether to extend a protocol, inherit other protocols, or use protocol composition. Explore static and dynamic dispatch and how these affect protocol extensions.
  • How to create a protocol with associated type, and how and why to use type erasure with generic types.
  • The different types of types, especially terminology that arises when discussing protocols.
See forum comments
Download course materials from Github
Previous: Lesson 1 Quiz Next: Combining Protocols