Skip to content

Chapter 2 of 7

Protocols and Extensions

A Protocol in Swift defines a blueprint of methods, properties, and other requirements that conforming types must implement. Classes, structs, and enums can all conform to a protocol, making protocols a central tool for defining shared interfaces across different kinds of types. A simple protocol might declare a draw() method, and any type that conforms to it must provide an implementation of that method.

Protocols can be enriched with default implementations through protocol extensions. By writing an extension on the protocol itself, developers can provide a body for any requirement, and conforming types will inherit that default behavior automatically. Conforming types can still override the default by providing their own implementation, which makes protocols a powerful tool for adding shared functionality without inheritance.

Protocol composition allows a function or type to require conformance to multiple protocols at once, using the & operator to combine protocol requirements. For example, a parameter declared as Codable & Hashable must conform to both protocols. Extensions in general add new functionality to existing types without modifying their source code, and they can add computed properties, methods, initializers, subscripts, nested types, and protocol conformances. However, extensions cannot add stored properties to a type, since stored properties must be declared in the type's original definition. Extensions are commonly used to organize code by grouping related functionality, often by protocol conformance, which keeps code well-structured without requiring subclassing.

All chapters
  1. 1Optionals and Safe Unwrapping
  2. 2Protocols and Extensions
  3. 3Closures and Functional Patterns
  4. 4Types: Structs, Classes, and Enums
  5. 5Generics and Type Abstraction
  6. 6Error Handling and Control Flow
  7. 7Memory Management, Properties, and Advanced Features

Drill it

Reading is not remembering. These come from the Swift Programming deck:

Q

What is an Optional in Swift?

An Optional in Swift represents a variable that can hold either a value or nil. It is declared using a ? after the type, e.g., var name: String?. Optionals enfo...

Q

How do you unwrap an Optional using if let?

You use optional binding with if let:if let unwrapped = optionalValue {  print(unwrapped)}This safely unwraps the optional and binds its value to a ne...

Q

What is the difference between Optional chaining and forced unwrapping?

Optional chaining uses ?. and returns nil if the optional is nil, failing gracefully.Forced unwrapping uses ! and crashes at runtime if the optional is nil.Exam...

Q

What is the nil-coalescing operator in Swift?

The nil-coalescing operator ?? provides a default value when an optional is nil.Example: let name = optionalName ?? "Unknown"If optionalName is nil, name is set...