← Back to Swift Course | Chapter 9: Inheritance & Protocols | Lesson 6 of 7

Protocol Extensions

A protocol extension lets you write actual code once, right on the checklist itself, so every type that conforms automatically gets that behavior for free.

Providing a Default Implementation

A protocol extension can implement a method directly, so any conforming type gets that behavior automatically without writing it themselves.

Example: Providing a Default Implementation

markup
protocol Greetable {
    var name: String { get }
}
extension Greetable {
    func greet() -> String {
        return "Hello, \(name)!"
    }
}
struct Visitor: Greetable {
    var name: String
}
let visitor = Visitor(name: "Sam")
print(visitor.greet())

Overriding a Default Implementation

A conforming type can still provide its own implementation of a method that a protocol extension already defines, which takes priority for that type.

Example: Overriding a Default Implementation

markup
protocol Greetable {
    var name: String { get }
}
extension Greetable {
    func greet() -> String {
        return "Hello, \(name)!"
    }
}
struct Robot: Greetable {
    var name: String
    func greet() -> String {
        return "BEEP \(name) BOOP"
    }
}
let robot = Robot(name: "Unit1")
print(robot.greet())
Common Mistakes
  1. Assuming a protocol extension's default implementation always runs; a conforming type can still override it with its own implementation.
  2. Forgetting that protocol extensions cannot add new required members -- they only provide default implementations or entirely new convenience methods.
  3. Adding stored properties in a protocol extension, which is not allowed; only computed properties and methods can be added.
Chapter Summary
  • A protocol extension provides a default implementation for a method or computed property.
  • Any conforming type automatically gets the default unless it provides its own implementation.
  • Extensions cannot add stored properties or new required members to a protocol.
  • This pattern reduces repeated boilerplate across many conforming types.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.