Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 146 ยท Protocols and Generics

Conditional Conformance

Learn Swift conditional conformance - how a generic type conforms to a protocol only when its parameters do, with Array, Optional, custom wrappers, Codable, Hashable and conflicts, with runnable code.

Is an array of integers equatable? Yes: [1, 2] == [1, 2] is true. Is an array of closures equatable? No, because closures cannot be compared. Yet both are the same generic type, Array. So how does Swift know that Array<Int> is Equatable but Array<() -> Void> is not? The answer is conditional conformance: a generic type conforms to a protocol only when its type parameters meet certain requirements.

This is one of the quiet foundations of the standard library, and you can use it in your own generic types. It makes wrappers behave like their contents: a box of equatable things is equatable, a pair of hashable things is hashable. This lesson builds on Generics and Protocol Extensions.

The syntax

You write an ordinary extension that adds a protocol conformance, followed by a where clause that states the condition.

Swift Box is Equatable only when its contents are

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The extension body is empty. When all stored properties are Equatable under the stated condition, Swift synthesizes the == implementation exactly as it does for ordinary structs (see Equatable, Hashable and Comparable). Box<Int>, Box<String> and Box<[Int]> are equatable. Because Box<Content> is equatable whenever Content is, Box<Box<String>> is too.

What happens when the condition fails

If you compare boxes whose contents are not equatable, the compiler tells you that no == applies:

Swift Contents that are not Equatable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The result is main.swift:13:13: error: operator function '==' requires that 'Plain' conform to 'Equatable', plus a note pointing at the conditional conformance of Box<Plain>. The conditional conformance exists, but its condition is unmet for Box<Plain>. Make Plain equatable (add : Equatable) and the same code compiles.

Conformances come in layers

Different conformances can have different conditions. A box may be Equatable when its content is Equatable, Hashable when it is Hashable, and Comparable when it is Comparable. Because Hashable refines Equatable, the stronger conformance implies the weaker one.

Swift Several conditional conformances

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

scores.sorted() works only because Labeled<Int> is Comparable, which holds because Int is. With Labeled<Double> as a dictionary key we use the Hashable conformance, which requires Double: Hashable. For Comparable we wrote the < ourselves, because synthesis for Comparable does not exist for structs; for Equatable and Hashable the empty bodies are enough.

How the standard library uses it

You have been relying on conditional conformances all along:

  • Array<Element>, Dictionary<Key, Value>, Set<Element>, Optional<Wrapped> and Range<Bound> are Equatable when their contents are, and Hashable when their contents are.
  • Array, Dictionary, Set and Optional are Codable when their elements are, and Sendable when their elements are.
  • Result<Success, Failure> is Sendable when both are.
Swift Containers in the standard library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

[[String]] is equatable because [String] is, which is equatable because String is. Each layer applies the same rule. A Set<[Int]> of coordinate paths works because Array<Int> is Hashable conditionally.

Conditional Codable and your own protocols

The pattern applies to protocols you invent. You can also write a conformance for an existing generic type, such as Array, for your own protocol:

Swift Your protocol conforming conditionally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

[[1, 2], [3]] works with no extra code, because [Int] is Describable, so [[Int]] is too. One conformance declaration covers infinitely many types. In the standard library, Codable works the same way: a struct Wrapper<T>: Codable where T: Codable is automatically synthesized.

Swift Conditional Codable with a generic wrapper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Envelope<Greeting> and Envelope<[Int]> are encodable; an Envelope<Plain> with a non-Codable payload is not. See Codable for the full story on Codable.

Rules and limits

Conditional conformance has a few rules worth knowing.

  1. One conformance per protocol per type. You cannot say Box: P where T == Int and also Box: P where T == String. That would make the conformance ambiguous.
  2. No overlapping conditions. If a conformance exists for some arguments, you cannot add a second one that applies to a subset.
  3. The conformance must be declared in an extension (or in the type's declaration) and, for synthesis, in the same file as the type.
  4. A refining protocol needs its parent. Hashable inherits from Equatable, so a Hashable conformance needs an Equatable conformance that holds under the same (or weaker) condition.

Violating the first rule looks like this:

Swift Two conformances for the same protocol (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler responds with main.swift:13:20: error: conflicting conformance of 'Wrapper<T>' to protocol 'Printable2'; there cannot be more than one conformance, even with different conditional bounds. The way out is to write one conformance with a broader condition, or make the behavior depend on another protocol that Int and String both adopt (for example Wrapper: Printable2 where T: CustomStringConvertible).

You can still provide different method behavior for different arguments without conformance, using constrained extensions: extension Wrapper where T == Int { func render() -> String { ... } } and a second one for String. Those are ordinary extensions, not protocol conformances, so they may coexist. The dispatch caveats are explained in Protocol Extensions.

When to use it

  • Wrappers and containers: if your generic type holds a value, let it be equatable, hashable, comparable or codable when the value is. It costs a one-line extension and users will expect it.
  • Protocols that compose structurally: Array: Describable where Element: Describable is more convenient than a free function.
  • Avoid it when the behavior differs per type. A single conformance with a condition must use the same implementation for all satisfying arguments. If Int and String need different logic, give them their own types or extensions.
  • Remember the cost of retroactive conformance. Conforming types you do not own (like Array) to a protocol you do own is safe. Conforming someone else's type to someone else's protocol can conflict with future library versions; Swift 6 warns about this as retroactive conformance.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does extension Box: Equatable where Content: Equatable {} mean?

    The where clause is a condition. The conformance exists only for specializations that satisfy it.
  2. 2. Why is [[Int]] Equatable?

    Conditional conformances apply layer by layer: Int to [Int] to [[Int]].
  3. 3. Which of these is NOT allowed?

    A type can conform to a protocol only once, even with different conditions. Constrained extensions without a conformance may coexist.
  4. 4. What does the compiler do for an empty extension Labeled: Hashable where Value: Hashable {}?

    When all stored properties are Hashable under the condition, Swift synthesizes the requirements, just like for non-generic structs.
  5. 5. Which standard-library type is Hashable only when its element is Hashable?

    Array<Element> conforms to Hashable conditionally; Int, Bool and String are unconditionally Hashable.

Summary

  • Conditional conformance lets a generic type adopt a protocol only when its type parameters satisfy a where clause.
  • For Equatable, Hashable and Codable an empty extension body is enough; the compiler synthesizes the rest. Comparable needs your own <.
  • It composes: [[Int]] is Equatable because [Int] is, because Int is.
  • A type can conform to a given protocol only once; conflicting or overlapping conditions are errors.
  • Prefer it for wrappers and containers so they behave like their contents.

Next: Noncopyable Types