Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 146 ยท Protocols and Generics

Protocol Extensions

Master Swift protocol extensions - add default behavior, constrain extensions with where clauses, extend standard library protocols, and understand static versus dynamic dispatch and its surprises.

A protocol says what a type must do. A protocol extension says what every conforming type can do for free. You write the code once, inside extension SomeProtocol { ... }, and every struct, class and enum that conforms gains it, including types written by other people and types that conform later.

This is the feature that makes Swift's standard library so compact. Methods like map, filter, sorted and contains are not written separately for arrays, sets and dictionaries; they live in extensions of Sequence and Collection and work on every conforming type, including yours. In this lesson you will learn to use extensions for defaults, for new helper methods, for conditional behavior with where clauses, and (most importantly) to understand the dispatch rules that decide which method actually runs. Those rules cause the best-known surprise in the language.

Adding behavior to every conformer

Anything you put in an extension of a protocol is available on all conforming types, without any change to those types.

Swift One extension, many types

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.

Neither shape declares report() or isLarge, yet both have them. The output shows square: area 16.0, rectangle: area 60.0, then false true. Note that report() and isLarge build on requirements of the protocol (name, area). That is the key to a good extension: express new behavior in terms of the protocol's own requirements.

Default implementations of requirements

When the extension implements a method that the protocol also declares, it acts as a default. Conforming types may skip it or replace it.

Swift Defaults that can be overridden

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.

ConsoleLogger needs no body at all. AuditLogger changes one detail and the default log picks it up. LoudLogger replaces the method entirely. The outputs are [log] started, [AUDIT] user signed in and DONE!.

Constrained extensions

Often a behavior only makes sense for some conforming types. A where clause restricts the extension to those. The extension then exists only when the condition holds.

Swift Extensions with where clauses

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.

Because Array, ClosedRange, Set and others all conform to Sequence, total() works on all of them; it appears only for numeric elements. The results are 10, 4.0, 5050, then true, false and red, green, blue. The standard library uses the same trick: sorted() and max() exist for arrays of Int or String (their elements are Comparable), but not for arrays of Bool.

A where clause can constrain the element (Element: Numeric), pin it exactly (Element == String), or require another protocol of the conforming type itself (where Self: Collection).

Using the extension where it does not apply

If you call an extension method on a type that does not satisfy the constraint, you get a clear error.

Swift Constraint not met (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 message is main.swift:8:13: error: referencing instance method 'total()' on 'Sequence' requires that 'String' conform to 'Numeric'. Strings cannot be added with Numeric arithmetic, so the method simply does not exist for them.

Extending protocols from the standard library

You can extend any protocol, including the ones you do not own. This is how you add helpers that feel native.

Swift Extending Collection safely

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.

names[safe: 10] returns nil instead of crashing with an out-of-range trap. The same two members work for strings (second character e) and empty arrays (nil), because both are Collections. Add helpers like this sparingly: a public extension on a standard protocol pollutes everyone's autocomplete, and a name that the standard library later adopts can cause conflicts.

The dispatch rule: static vs. dynamic

Here is the part that surprises people. There are two ways Swift can call a method:

  • Dynamic dispatch: the call is resolved at run time, using the actual type of the value. This is how overriding works.
  • Static dispatch: the call is resolved at compile time, using the declared type of the variable.

For protocols, the rule is:

A method that is declared in the protocol (a requirement) is dispatched dynamically. A method that exists only in an extension is dispatched statically, according to the type the compiler sees.

Watch what that does when the type is a protocol:

Swift Requirement versus extension-only method

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.

sound() is a requirement, so animal.sound() correctly reaches Dog's woof. But describe() is not a requirement, so when the variable's type is Animal, the compiler picks the extension's version at compile time. The two describe() calls print A dog says woof and An animal says woof, even though both talk to the same dog. (Inside the extension's describe(), the call to sound() is dynamic, which is why the word woof still appears.)

This is not a bug; it is a rule you must know. It means:

If you want a method to be customizable by conforming types, declare it in the protocol, then provide the default in the extension. If you only put it in the extension, a conforming type's "override" will only be used when the variable has the concrete type, and silently ignored through the protocol type. Nothing warns you.

The fix is to make describe() a requirement:

Swift Fix: add describe to the protocol

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.

Now animal.describe() prints A dog says woof, because the call is dispatched dynamically to the type's own method.

The same rule explains constrained defaults

Swift picks the most specific applicable extension. When two extensions could apply, the one with the more constraints wins:

Swift The most specific extension wins

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 numeric box uses the general version (3 items); the string box uses the more specific one (2 strings: a/b). The compiler decides using the type's known generics at the call site. This is also static, which is why a generic function that is only told T: Container would use the general version. Associated types are explained in Associated Types.

When to use extensions on protocols

  • Share implementation across types that have nothing else in common, instead of a base class. This is the "protocol-oriented" alternative to inheritance.
  • Provide sensible defaults so conformers have little to write.
  • Add derived behavior that depends only on the requirements (report() above).
  • Constrain helpers so they appear only where they make sense.
  • Avoid: adding a different meaning to an existing name; overriding a method that is not a protocol requirement and expecting dynamic behavior; heavy public extensions on standard protocols in libraries.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a method inside extension MyProtocol { ... } give you?

    Protocol extensions add behavior to all conforming types without touching them.
  2. 2. A method exists only in a protocol extension (not declared in the protocol). A conforming struct defines the same method. Called through a variable of the protocol type, which runs?

    Methods that are not requirements use static dispatch based on the declared type, so the extension version runs through the protocol type.
  3. 3. How do you make a default method customizable through the protocol type?

    Requirements are dispatched dynamically; the extension then only supplies a default body.
  4. 4. What does extension Sequence where Element: Numeric do?

    A where clause restricts the extension, so total() exists only for numeric elements.
  5. 5. When two extensions could both supply a method, which is chosen?

    Swift picks the most specific applicable extension; the constrained one beats the unconstrained one.

Summary

  • A protocol extension adds methods and computed properties to every conforming type, including standard-library and third-party types.
  • If the extension implements a protocol requirement, it is a default; conformers may override it.
  • Use where clauses to restrict an extension by element type, by equality (Element == String) or by other protocols.
  • Requirements are dispatched dynamically; methods that exist only in an extension are dispatched statically by declared type. Declare anything customizable in the protocol itself.
  • The most specific applicable extension wins.
  • Extensions can add methods, computed properties, subscripts and initializers, but never stored properties.

Next: Protocol Composition and Delegation