skip to content

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%

answer

  1. generic type, conditional protocol
  2. where clause on the conformance
  3. one conformance per protocol
  4. inherited protocols stated explicitly
  5. dynamic casts check the condition

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.

solid answer

~40 s

`extension LogEntry: Equatable where Payload: Equatable {}` says `LogEntry<String>` is `Equatable` and `LogEntry<RawBytes>` is not; using `==` on the latter is a compile error naming the conditional requirement. The compiler can synthesize `==` and `hash(into:)` in such an extension when it sits in the type's own file. The limits: a type has **at most one** conformance to a protocol, so two conformances with different `where` bounds are rejected; a conditional `Hashable` does **not** imply `Equatable`, which must be declared on its own; and a dynamic cast such as `value as? any Equatable` succeeds only when the condition holds for the value's actual type arguments. The standard library uses this for `Array`, `Optional` and `Dictionary` with `Equatable`, `Hashable` and `Codable`.

code

swift · 18 lines
swift
struct LogEntry<Payload> {
    var level: Int
    var payload: Payload
}

// The compiler synthesizes == and hash(into:) only under these conditions.
extension LogEntry: Equatable where Payload: Equatable {}
extension LogEntry: Hashable where Payload: Hashable {}

struct RawBytes { var bytes: [UInt8] }   // deliberately not Equatable

let boot = LogEntry(level: 1, payload: "boot")
print(boot == LogEntry(level: 1, payload: "boot"))   // true
print(Set([boot, boot]).count)                        // 1

let raw: Any = LogEntry(level: 2, payload: RawBytes(bytes: []))
print(raw is any Equatable)                           // false
print((boot as Any) is any Hashable)                  // true

go deeper

for a junior

Recall that [Int] can be compared with == because Array is Equatable only when its elements are.

for a middle

Explain the syntax and the effect: the where clause on the conformance limits which specializations of the generic type conform.

for a senior

Name the limits you have hit: one conformance per protocol, inherited protocols declared explicitly, and runtime casts that depend on the actual type arguments.

for a principal

Decide which generic wrappers in shared modules should forward Equatable, Hashable, Codable and Sendable conditionally, since each forwarded conformance becomes part of the public contract.

## What a conditional conformance says A **conformance** states that a type satisfies a protocol. For a generic type, a **conditional conformance** states that only some specializations do: those whose type arguments satisfy a `where` clause written on the conformance itself. ```swift extension LogEntry: Equatable where Payload: Equatable {} ``` reads as: `LogEntry<String>` is `Equatable`, `LogEntry<RawBytes>` is not. Swift Evolution proposal SE-0143 introduced the feature, and the CHANGELOG records the standard library adopting it in Swift 4.1, so every supported toolchain has it. The proposal's motivating example is the one interviewers quote: `extension Array: Equatable where Element: Equatable`. ## What it buys you - **Composition of standard behaviour.** `[[Int]]` and `[Int?]` compare with `==` because `Array` and `Optional` forward `Equatable` from their contents. The same holds for `Hashable` and, via `Encodable` and `Decodable`, for `Codable`. - **Synthesis on your own types.** When the conditional extension sits in the same file as the type, the compiler synthesizes `==` and `hash(into:)` as it would for an unconditional conformance, so `extension LogEntry: Equatable where Payload: Equatable {}` needs no body. - **Precise errors.** Calling `==` on a `LogEntry<RawBytes>` fails at compile time with "operator function '==' requires that 'RawBytes' conform to 'Equatable'", plus a note pointing at the conditional conformance. ## The limits interviewers probe | Limit | What the compiler or runtime does | |---|---| | Only one conformance per protocol | Two `extension Box: P where ...` declarations with different bounds are rejected: "there cannot be more than one conformance, even with different conditional bounds". | | No implied inherited conformances | `extension Box: Hashable where T: Hashable {}` alone is rejected: it "does not imply conformance to inherited protocol 'Equatable'". | | Conditions are static | The bound applies to the generic arguments; one value cannot conform while another of the same specialization does not. | | Runtime casts check the bound | `x as? any Equatable` succeeds only when the actual type arguments satisfy it (implemented in Swift 4.2). | The second limit is deliberate. Swift could guess `Equatable where T: Hashable`, but a looser bound (`where T: Equatable`) is often what the author wants. The compiler therefore makes you pick, and its fix-its offer the relaxed bound, the same bound, or a different one. ## A worked example 1. Declare the generic type: `struct LogEntry<Payload> { var level: Int; var payload: Payload }`. 2. Add `extension LogEntry: Equatable where Payload: Equatable {}` and `extension LogEntry: Hashable where Payload: Hashable {}` in the same file. 3. `LogEntry(level: 1, payload: "boot")` now works with `==` and as a `Set` element. 4. `LogEntry(level: 2, payload: RawBytes(bytes: []))` stored as `Any` fails an `is any Equatable` check, because `RawBytes` is not `Equatable`. ## Conformance versus constrained extension The two look alike and are often confused: - `extension LogEntry: Equatable where Payload: Equatable` adds a **conformance**: `LogEntry<String>` can be passed wherever an `Equatable` is required. - `extension LogEntry where Payload: Numeric { func scaled() ... }` adds **members** only: no new conformance, nothing for generic code that asks for a protocol. Only the first is subject to the one-conformance-per-protocol rule. When several **constrained extensions** provide the same default implementation, Swift picks the most specialized one; that tie-breaking rule does not extend to conformances. The grammar of `where` clauses in general belongs with generic constraints. ## Defaults inside a conditional conformance A conditional conformance is checked once for the generic type, with only its stated conditions known. If `Logger` has a default that only applies `where Self: Equatable`, a generic `LogBox<T>` that is `Equatable` only when `T` is will, through the protocol, receive the unconstrained default: when the conformance was checked, `LogBox<T>` was not known to be `Equatable`. A direct call on `LogBox<Int>` can still select the constrained one, so the same value can print two answers depending on how it is called. ## Common slips - Writing `Hashable where T: Hashable` and expecting `Equatable` to follow. - Trying a second conformance for a different bound instead of one conformance with a broader implementation. - Assuming `is any Equatable` is true for every specialization of a type that is conditionally `Equatable`.

  • Why does Swift reject two conditional conformances of one generic type to the same protocol with different where clauses?
    A conformance is a single, process-wide fact about a type and a protocol, so Swift allows one per pair. With two bounds a type argument could satisfy both, and there would be no single answer to which implementation it uses. The compiler reports "conflicting conformance ... there cannot be more than one conformance, even with different conditional bounds". Folding the behaviour into one conformance, or adding a constrained extension that only adds members, avoids it.
  • Your LogEntry<Payload> is Equatable when Payload is. Does a value stored as Any pass an `is any Equatable` check?
    Only when its actual `Payload` is `Equatable`. The runtime evaluates the conditional requirement against the value's real type arguments, so `LogEntry<String>` passes and `LogEntry<RawBytes>` fails. The CHANGELOG records this runtime query arriving in Swift 4.2, one release after conditional conformances themselves.

  • A conditional Hashable conformance automatically makes the type conditionally Equatable.
  • A type can conform to one protocol twice with different where clauses.
  • When two conditional conformances overlap, Swift picks the most specialized one.
  • LogEntry is Equatable for every Payload once the conditional extension exists.
  • Dynamic casts ignore the condition and succeed for any type arguments.