Coding/Learn/swift/swift protocols and extensions
Swift Foundational Course
01.Introduction, Safety Philosophy & The Toolchain
02.Constants (let), Variables (var) & Type Inference
03.Strings, String Interpolation & Multiline Literals
04.Operators, Range Types & Nil-Coalescing
05.Control Flow: If, Switch Pattern Matching & Guard Statements
06.Optionals, Optional Binding & Optional Chaining
07.Arrays, Sets & Higher-Order Collection Operations
08.Dictionaries, Default Lookups & Tuples
09.Loops, Defer Execution & Labeled Statements
10.Functions, Argument Labels & In-Out Parameters
11.Closures, Trailing Closures & Shorthand Arguments
12.Enums, Raw Values & Associated Values (Tagged Unions)
13.Error Handling: Throwing Functions, Do-Catch & Try Options
14.Structures (struct), Value Semantics & Mutating Methods
15.Classes, Reference Semantics & Inheritance
16.Automatic Reference Counting (ARC), Weak & Unowned References
17.Properties: Stored, Computed, Observers (didSet) & Lazy
18.Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)
19.Generics, Type Constraints & Associated Types
20.Capstone: Production Async/Await Cache & JSON API Engine
Course Certificate0%

Complete all lessons to earn

LearnProtocols, Protocol Extensions & POP (Protocol-Oriented Programming)
18 / 20 0%
Lesson 18 of 20
10 mins read

Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)

PreviousNext Lesson
In Plain English

Swift is a Protocol-Oriented language. Learn how protocols define blueprints of methods and properties, how extensions add functionality to existing types without subclassing, and how protocol extensions provide default implementations.

The Mental Model

"A protocol is like a job contract: it states that anyone holding the title of "Driver" must know how to steer and brake. A protocol extension is a free company training manual providing a standard default steering technique to anyone who signs the contract."

Deep Dive: How It Works

Protocols: Define requirements (properties with { get set }, methods, inits) without concrete implementations.

Extensions: Add new methods, computed properties, and protocol conformances to existing types (even types you don’t own, like String or Int).

Protocol Extensions: Provide default method implementations for protocols, enabling mixin-like trait composition without inheritance.

Common Standard Protocols: Identifiable, Equatable, Hashable, Comparable, and CustomStringConvertible.

Syntax Blueprint

protocol Describable {
    var description: String { get }
}
extension Describable {
    func printDescription() { print(description) }
}

Define protocol contracts and extend protocols with default implementation methods.

PointCore Rules to Remember

Point star
Protocol-Oriented Programming (POP): Prefers composition via protocols over deep class inheritance hierarchies.
Point star
Retroactive Modeling: Extend existing types with custom protocol conformances: extension Int: MyCustomProtocol {}.
Point star
Multiple Protocol Conformance: Structs and classes can conform to any number of protocols: struct User: Codable, Identifiable {}.

Common Beginner Traps & How to Fix Them

Mistake:Trying to add stored properties inside an extension.

Why it happens: Extensions can only add computed properties and methods, not stored instance state.

How to fix: Declare stored properties in the main type definition and use extensions for computed helpers and protocol conformance.

Pro Tip: Conform to CustomStringConvertible and implement var description: String to control how your custom types display in print() statements.

Live Interactive Example

Hit Run Code to see it live
Protocol with Default Extension and CustomStringConvertible
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Output Console
Click "Run Code" to view the rendered output.
How it works: Member gained greet() and description implementations automatically from the Greetable protocol extension.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Extend Int with Squared Helper

  • PointWrite an extension on Int with a computed property var squared: Int { self * self }.
  • PointIn top-level code, declare let num = 8 and print "8 squared: \(num.squared)".
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates