skip to content

Default Implementations and Dispatch

Protocol extensions add default implementations, but a method not declared as a requirement is dispatched statically. Interviewers ask why a conforming type's own version is skipped.

on this pageshow

explore

questions

5

In Swift, how does a protocol extension supply a default implementation for a requirement, and when does a conforming type's own version replace it?

level: middleimportance: must knowfreq 75%

answer

  1. extension on the protocol itself
  2. requirement declared in the protocol body
  3. same name, argument labels and types
  4. conformer's member wins through the protocol too

basics

~20 s

A protocol extension can implement a method or computed-property requirement, and conformers that declare nothing get it. A conformer declaring a member with the same name, argument labels and types replaces that default everywhere, including calls through the protocol.

solid answer

~40 s

You write `extension Logger { func log(_ message: String) { ... } }` for a requirement the protocol body declares. Any conformer that does not implement `log(_:)` itself gets this **default implementation**; one that does implement it with the same name, argument labels and types uses its own version, and because `log(_:)` is a requirement that choice holds through `any Logger` and generic code as well, not just on the concrete type. No `override` keyword is involved: on a struct it is a compile error. The trap is a near miss: a method with a different argument label, such as `log(message:)`, is a new overload, the default keeps running, and the compiler can stay silent. A requirement with a default is still called directly, never with optional chaining, unlike an `@objc optional` requirement.

code

swift · 26 lines
swift
protocol Logger {
    var name: String { get }
    func log(_ message: String)
}

extension Logger {
    // Default implementations of both requirements.
    var name: String { "logger" }
    func log(_ message: String) {
        print("[\(name)] \(message)")
    }
}

struct SilentLogger: Logger {}           // takes both defaults

struct FileLogger: Logger {
    var name: String { "file" }          // replaces the default name
    func log(_ message: String) {        // replaces the default log(_:)
        print("file <- \(message)")
    }
}

let loggers: [any Logger] = [SilentLogger(), FileLogger()]
for logger in loggers { logger.log("started") }
// [logger] started
// file <- started

go deeper

for a junior

Recall the shape: the requirement sits in the protocol body, the default sits in an extension of the protocol, and a conformer may skip it.

for a middle

Explain the matching rule: same name, argument labels and types replace the default everywhere; a different label is just an overload and the default keeps running.

for a senior

Show you catch near misses in review: a renamed label or a changed parameter type silently falls back to the default, and the compiler may not warn about it.

for a principal

Weigh defaults as API design: each one is a customization point you promise to honour, and adding a requirement with a default changes behaviour for conformers that already had a same-named member.

## What a default implementation is A Swift **protocol** lists requirements: methods, properties, initializers and subscripts a conforming type must provide. A **protocol extension** (`extension Logger { ... }`) adds code to the protocol itself, and when one of its members has the same signature as a requirement, it becomes that requirement's **default implementation**. Every conforming type that does not provide its own version gets the default automatically. ```swift protocol Logger { var name: String { get } func log(_ message: String) } extension Logger { var name: String { "logger" } func log(_ message: String) { print("[\(name)] \(message)") } } ``` With these defaults, `struct SilentLogger: Logger {}` compiles with an empty body. The Swift book states the rule directly: if a conforming type provides its own implementation of a required method or property, that implementation is used instead of the one the extension provides. ## When the conformer's version replaces the default A conformer **replaces** the default by declaring a member that matches the requirement: - the same base name (`log`); - the same **argument labels** (`_` here), while the internal parameter names do not matter, so `log(_ text: String)` matches; - the same parameter and return types, and for properties at least the access the requirement asks for (`{ get }` can be satisfied by a computed property, a `let` or a `var`). No keyword marks the replacement. `override` belongs to class inheritance: on a struct member the compiler rejects it with "'override' can only be specified on class members". Because `log(_:)` is a **requirement**, the conformer's choice is honoured at every call site: on the concrete type, through an existential `any Logger`, inside a generic function `func run<L: Logger>(_ logger: L)`, and even when the default `log(_:)` itself reads `name`. That last point lets a default act as a template: it calls other requirements, and each conformer fills in only the pieces it cares about. | Conformer declares | What `(x as any Logger).log("hi")` runs | |---|---| | nothing | the extension's default | | `func log(_ message: String)` | the conformer's method | | `func log(_ text: String)` | the conformer's method (internal name ignored) | | `func log(message: String)` | the default: this is a new overload | ## Near misses keep the default silently The last table row is the classic bug. A conformer meant to replace `log(_:)` but wrote `log(message:)`, or changed `String` to `String?`. Because a default exists, the conformance is still complete, the type compiles, and the default keeps running. The compiler has a "nearly matches defaulted requirement" warning, but it does not fire for every near miss: the Swift 6.4 compiler printed nothing for a mismatched label or an optional parameter in a plain struct. Reviewers have to compare signatures with the protocol, or a test has to call the method through the protocol. ## Constrained extensions add conditional defaults An extension can carry a `where` clause, such as `extension Collection where Element: Numeric`, and its members exist only for conformers that meet the condition. When a conformer satisfies several constrained extensions that implement the same requirement, the book's rule is that Swift uses the implementation with the **most specialized constraints**. (Writing the `where` clauses themselves is generic-constraints material; here the point is only which default a conformer ends up with.) ## Defaults are not optional requirements Two features both let a conformer skip a member, and they are easy to confuse: 1. A **requirement with a default** always has an implementation, so callers invoke it directly. 2. An **`@objc optional` requirement** may have no implementation at all, so callers use optional chaining, and it exists only on `@objc` protocols. ## What extensions cannot default - **Stored properties**: extensions cannot add stored properties, so a default for a property requirement must be computed. A conformer may still satisfy it with its own stored property. - **Members that are not requirements**: an extension can add any method, but if the protocol body does not declare it, it is not a customization point and conformers cannot replace it through the protocol. That rule decides which code runs when a conformer defines a method with the same name, and it is the source of the best-known surprise in protocol-oriented Swift. ## In an interview Say where the default lives, state the matching rule (name, labels, types), show that the conformer wins through `any Logger` as well as on the concrete type, and name the near-miss trap with its fix: keep signatures identical, and test through the protocol.

  • Can a Swift default implementation call other requirements of the same protocol, and which version runs?
    Yes. Inside `extension Logger`, `self` is the conforming value seen through the protocol, so a call to another **requirement** such as `name` reaches the conformer's own implementation when it has one. That is how a default `log(_:)` can format with a conformer-specific `name`. A call to a member that exists only in the extension does not get this treatment; it is fixed at compile time.
  • Can a Swift protocol extension give conformers a default stored property?
    No. Extensions cannot add stored properties, so a default for `var name: String { get }` has to be a computed property. A conformer can still satisfy that requirement with its own stored `let name` or `var name`, and that stored property then replaces the computed default.

  • A conformer must mark its method override to replace a protocol extension's default.
  • A method with a different argument label still replaces the default implementation.
  • Requirements with defaults are called with optional chaining, like optional requirements.
  • A protocol extension can give every conformer a default stored property.
  • Once a default exists, calls through any Logger always run the default.
open as a page

A Swift Logger protocol's extension adds a format(_:) helper the protocol never declares; why is a conformer's own format(_:) ignored when called through the protocol?

level: seniorimportance: must knowfreq 70%

basics

~20 s

Only protocol requirements reach a conformer's own implementation through the protocol. An extension-only member like format(_:) is chosen at compile time from the static type, so through any Logger, a generic parameter or self in the extension, the extension's version runs.

open as a page

In Swift, how does a conditional conformance such as extension Array: Equatable where Element: Equatable work, and what are its limits?

level: seniorimportance: should knowfreq 50%

basics

~20 s

A generic type conforms to a protocol only when its type arguments meet the where clause, so [Int] is Equatable and [Any] is not. A type gets one conformance per protocol, and inherited protocols must be stated separately.

open as a page

Why does the Swift 6 compiler warn about extension Date: Identifiable in an app, and what does marking it @retroactive change?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Date and Identifiable both come from other modules, so this is a retroactive conformance: if Foundation later declares the same one, which implementation wins is not under your control. Writing @retroactive just acknowledges the risk and silences the warning.

open as a page

As the lead of a multi-module Swift app, what rules would you set for retroactive conformances and public protocol extensions across modules?

level: principalimportance: should knowfreq 30%

basics

~20 s

Give each conformance one owner: the type's module or the protocol's. Keep unavoidable retroactive conformances in the app target, marked and justified, prefer wrapper types, and choose deliberately which protocol members are requirements and who may extend shared protocols.

open as a page