skip to content

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%

answer

  1. requirement or not?
  2. picked by the static type
  3. self inside the extension
  4. declare it in the protocol body

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.

solid answer

~40 s

`format(_:)` is not a **requirement**, so a conformance never records an implementation for it. Every call is resolved at compile time from the **static type** of the expression. On a value typed `ConsoleLogger` the compiler finds `ConsoleLogger.format(_:)`; on `any Logger`, on a generic `L: Logger`, and on `self` inside the protocol extension it only knows the protocol, so it binds the extension's `format(_:)`. That is why the default `log(_:)`, which calls `format`, prints the default prefix even for `ConsoleLogger`. The conformer's method shadows the helper; it does not override it. The fix is to declare `func format(_ message: String) -> String` in the protocol body and keep the extension body as its default, which turns it into a customization point.

code

swift · 27 lines
swift
protocol Logger {
    func log(_ message: String)
}

extension Logger {
    // Default implementation of the requirement.
    func log(_ message: String) {
        print(format(message))
    }
    // Extension-only helper: NOT declared in the protocol.
    func format(_ message: String) -> String {
        "[default] \(message)"
    }
}

struct ConsoleLogger: Logger {
    func format(_ message: String) -> String {
        "[console] \(message)"
    }
}

let concrete = ConsoleLogger()
let existential: any Logger = concrete

print(concrete.format("a"))     // [console] a
print(existential.format("b"))  // [default] b
concrete.log("c")               // [default] c

go deeper

for a junior

Recall that a method in a protocol extension that the protocol body does not list is not something conformers can replace through the protocol.

for a middle

Explain the rule: requirements are looked up through the conformance, extension-only members are bound at compile time from the static type of the expression.

for a senior

Trace each call site in a bug report: concrete type, any Logger, generic parameter, self inside the extension, and a class whose superclass took the default.

for a principal

Treat the list of requirements as a public contract: promoting a helper to a requirement changes which code runs for every conformer that already had a same-named method.

## The setup A team defines a `Logger` protocol with one requirement, `log(_:)`. Its extension supplies a default `log(_:)` and a helper `format(_:)` that adds a prefix. `ConsoleLogger` conforms and writes its own `format(_:)`, expecting every log line to use it. Some lines do, many do not. ```swift protocol Logger { func log(_ message: String) } extension Logger { func log(_ message: String) { print(format(message)) } func format(_ message: String) -> String { "[default] \(message)" } } struct ConsoleLogger: Logger { func format(_ message: String) -> String { "[console] \(message)" } } ``` ## Requirements versus extension-only members Swift draws a hard line between two kinds of protocol member: - A **requirement** is declared in the protocol body. Each conformance records which implementation satisfies it: the conformer's own member or the extension's default. A call through the protocol looks that up for the actual conforming type, so it is **dynamically dispatched**. - An **extension-only member** is declared only in an extension. No conformance records anything for it, so a call is resolved at compile time from the **static type** of the expression, exactly like a call to an ordinary function. It is **statically dispatched**. `ConsoleLogger.format(_:)` is therefore not an override of anything. It is a second, unrelated method that **shadows** the extension's helper when the compiler can see the concrete type. Swift's library-evolution document states the same rule in one line: members of protocol extensions that do not satisfy protocol requirements are not overridable, even when the conforming type is a class. ## Which version runs at each call site | Call site | Static type | `format(_:)` that runs | |---|---|---| | `ConsoleLogger().format("a")` | `ConsoleLogger` | ConsoleLogger's | | `(c as any Logger).format("b")` | `any Logger` | extension's | | `func use<L: Logger>(_ l: L) { l.format("g") }` | `L`, known only as a `Logger` | extension's | | `format(message)` inside the default `log(_:)` | `Self`, known only as a `Logger` | extension's | The third row surprises people who know that the optimizer specializes generics: specialization never changes which method a generic body means, so a generic `L: Logger` behaves like the protocol. The fourth row is why even `ConsoleLogger().log("c")` prints `[default] c`: the outer call reaches the default `log(_:)`, and inside it `format` was bound when the extension was compiled. Writing `self.format(message)` changes nothing, because `self` there is still only a `Logger`. ## The fix: make it a customization point Declare the helper in the protocol body and keep the extension body as its default: 1. Add `func format(_ message: String) -> String` to `protocol Logger`. 2. Leave the extension's `format(_:)` unchanged; it is now the default implementation. 3. Re-run the call sites: through `any Logger`, generics and the default `log(_:)`, ConsoleLogger's `format(_:)` now runs. If the helper is meant to stay fixed for every conformer, the opposite fix is to give it a name conformers will not reuse, so nobody believes they are customizing it. ## Classes do not escape the rule Two class-specific traps follow from the same mechanism: - A conforming class cannot override an extension-only member: it can only shadow it, as a struct does. Neither `@objc` nor `final` can be written on a member of a protocol extension; the compiler rejects both. - When a **base class** adopts `Logger` and takes a **default** for a requirement, a subclass that writes the same method is not used through the protocol: the base class's conformance already chose the default, and `override` is rejected because the superclass has no such method. Implementing the requirement in the base class, then overriding it in the subclass, fixes it. ## Diagnosing it in a review - Search the protocol body for every method the extension defines; anything missing is extension-only. - Ask which static type each call site sees: concrete, `any Logger`, a generic parameter or `self` in the extension. - Write the test through the protocol (`let logger: any Logger = ConsoleLogger()`), because a test on the concrete type passes either way. How a conformance records its implementations at the machine level, and what the optimizer does with static calls, is material on method call mechanisms; the interview answer here is the language rule: requirements dispatch on the conformer, extension-only members on the static type.

  • A base class adopts Swift's Logger and takes the default format(_:) requirement; a subclass defines its own format(_:). Which runs through any Logger?
    The default. The base class's conformance chose the extension's implementation, and the subclass method overrides nothing, so writing `override` is rejected with "method does not override any method from its superclass". The fix is to implement `format(_:)` in the base class itself; the subclass then overrides that method with `override`, and calls through the protocol reach it.
  • Logger has an unconstrained default for a requirement and a second default in an extension where Self: Equatable. Which does a generic LogBox<T> get through the protocol when it is Equatable only for Equatable T?
    The unconstrained one. `LogBox<T>`'s conformance to `Logger` is checked once for every `T`, and at that point `LogBox` is not known to be `Equatable`, so the constrained default does not apply. A direct call on `LogBox<Int>` can still pick the constrained version, because there the static type is known to be `Equatable`. The Swift 6.4 compiler shows both results in one program.

A printed form with blank fields: each office fills in the blanks, and every copy shows that office's entries. Wording printed on the form itself is the same on every copy; an office that pins its own wording beside the form changes only what visitors read at that desk, never what the form says.

  • The conformer's format(_:) overrides the extension method, so it always runs.
  • Writing override on the conformer's method makes the protocol call it.
  • Generic code calls the concrete type's method because generics get specialized.
  • Marking the extension method @objc makes it dynamically dispatched.
  • Calling self.format inside the extension reaches the conformer's version.