0Pricing
Swift Academy · Lesson

Default Implementations in Extensions

Provide shared behavior via protocol extensions.

The Problem

Protocols declare requirements but provide no behavior. If every conforming type had to repeat the same logic, you would duplicate code. Protocol extensions solve this by supplying default implementations.

protocol Greeter {
    func greet() -> String
}

Adding a Default

An extension on the protocol can implement a requirement. Conforming types get that behavior for free unless they override it.

protocol Greeter { func greet() -> String }

extension Greeter {
    func greet() -> String { "Hello!" }
}

struct Robot: Greeter {}
print(Robot().greet())

All lessons in this course

  1. Protocols as Contracts
  2. Default Implementations in Extensions
  3. Protocol Composition
  4. Conditional Conformance
← Back to Swift Academy