Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 146 ยท Protocols and Generics

Protocol Composition and Delegation

Learn Swift protocol composition with &, the delegate pattern, weak delegates, class-bound protocols with AnyObject, retain cycles and optional delegate methods, with runnable examples.

Real types rarely fit into one neat box. A thing on screen might be both printable and comparable. A function might need an argument that can be saved and also described. A screen might need to tell its owner "the user tapped Done" without knowing who the owner is. Swift handles these needs with two ideas that are closely related: protocol composition, which combines several protocols into one requirement, and the delegate pattern, which uses a protocol as a contract between two objects.

This lesson builds on Protocols and Protocol Extensions. You will learn how & works, how to give a composition a name, how to write a delegate that does not leak memory, and why delegate protocols are usually restricted to classes.

Combining protocols with &

Suppose two small protocols describe two abilities:

Swift
protocol Named { var name: String { get } }
protocol Aged { var age: Int { get } }

A function that greets a person needs both. Instead of inventing a third protocol, join the two with an ampersand. Named & Aged means "any type that conforms to Named and also conforms to Aged".

Swift A composition as a parameter type

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.

Inside birthdayCard, the parameter exposes both name and age. A Pet is Named but not Aged, so passing a Pet to birthdayCard would not compile. The composition is a requirement on the argument, not a new type you must declare anywhere. Compositions can have as many parts as you like: A & B & C.

What happens when a requirement is missing

The compiler checks every part of the composition. Here a Pet is passed where Named & Aged is expected:

Swift Missing half of a composition (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 error is main.swift:12:25: error: argument type 'Pet' does not conform to expected type 'Aged'. Notice that it names only the missing protocol; the compiler does not complain about Named because Pet already has it. The fix is to make Pet conform to Aged, or to change the function so it asks for less.

Naming a composition with typealias

Long compositions get noisy when repeated. A typealias gives the combination a name without creating a new protocol.

Swift typealias for a composition

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 two types are unrelated, yet both can sit in one array because the array's element type is the composition. We wrote any Displayable here; the keyword any marks a type that is a protocol (or composition) used as a type. Opaque and Existential Types explains the difference between any and some in detail. For now, read any Displayable as "some value, of any type, that conforms to Displayable".

A typealias for a composition does not create a protocol. You cannot write extension Displayable { ... } for it, and you cannot conform to it with extra requirements. If you want a real, extendable protocol that bundles others, declare one that inherits from them: protocol Displayable: CustomStringConvertible, Identifiable2 {}. Then types conform once and you can add extensions and default implementations to Displayable.

Composition with a class or AnyObject

One part of a composition may be a class, and one part may be the special AnyObject requirement, which means "this must be an instance of some class". That is how a function can demand a reference type that also has some ability.

Swift Class plus protocol, and AnyObject

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 first call prints Counter at 42, then Counter at 0: the function reset the very object you passed in, because a class instance is shared. For the struct, show resets a copy, so the original Flag would stay on. A requirement of AnyObject is precisely what delegate protocols use, as you will see next.

The delegate pattern

A delegate is an object that another object hands some decisions or events to. The owner says "I do not know what should happen when the download finishes; whoever my delegate is will decide". The pattern is made of three pieces:

  1. A protocol that lists the messages the owner may send (the contract).
  2. A property on the owner that holds something that conforms to the protocol.
  3. A type that conforms and does the real work.

The owner stays reusable because it depends only on the protocol.

Swift A first delegate

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 output is progress at 40%, 80% and 100%, then the finishing line. Downloader knows nothing about ProgressPrinter; it only calls the two protocol methods. The delegate is optional (DownloaderDelegate?), so delegate?.downloader(...) quietly does nothing when no delegate is set.

By convention the first parameter of a delegate method is the sender (_ downloader: Downloader). That lets one delegate serve several owners and tell them apart, and it gives the delegate easy access to the owner's state, as ProgressPrinter does above. Method names read like sentences: didReceive, willBegin, shouldRetry. Names with will and did are notifications. Names with should ask a question and return a Bool or a value.

Why delegates are weak, and why that needs AnyObject

Look at who owns whom. Typically a view controller owns a downloader (a strong reference), and the downloader points back to the view controller as its delegate. If both references were strong, neither object could ever be freed. This is a retain cycle, explained in Memory Management with ARC. The fix is to make the delegate reference weak.

But weak only makes sense for class instances, because only classes are reference-counted. So Swift only allows weak on a protocol type when the protocol is class-bound, which you declare by inheriting from AnyObject. Forgetting it gives an error:

Swift weak without a class-bound 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 stops at weak var listener: Listener? with main.swift:6:14: error: 'weak' must not be applied to non-class-bound 'any Listener'; consider adding a protocol conformance that has a class bound. The fix is one word: protocol Listener: AnyObject.

Now see what the cycle looks like when it is real. Both classes below print a message when they are freed (deinit), so you can tell whether memory was released.

Swift Strong delegate leaks, weak delegate does not

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 "safe" scenario prints both freed lines as soon as the function returns. The "leaky" scenario prints nothing after leaky handles start: nothing is freed, because each object keeps the other alive. In a real app that leak lasts until the process ends. When the delegate relationship is "child talks to parent", make it weak.

A weak property must be optional and must be var, because ARC sets it to nil automatically when the object disappears. That is a feature: if the delegate has gone away, delegate?.something() simply does nothing. It never crashes with a dangling pointer.

Optional delegate methods

Objective-C protocols have @objc optional methods, but those need the Objective-C runtime, which Linux does not have and modern Swift code avoids. In pure Swift the standard technique is a protocol extension with default implementations: every method has a do-nothing default, and a delegate overrides only the ones it cares about.

Swift Default implementations make methods optional

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.

OnlyFinish implements one method and silently inherits no-ops for the other, so the first timer prints only Liftoff!. The second delegate prints the countdown and Done.. One caveat from Protocol Extensions: the extension's defaults are only called dynamically because the methods are also declared in the protocol. If you left them out of the protocol body and put them only in the extension, a delegate's own version would be ignored when called through the protocol type.

Delegate or closure?

Swift also gives you closures, and a closure property is often simpler than a whole protocol:

Swift
final class Button {
    var onTap: (() -> Void)?
}

A rough guide:

  • Use a closure for a single event with one outcome, such as "tapped" or "finished".
  • Use a delegate protocol when there are several related callbacks that belong together, when the delegate needs to answer questions (shouldRetry), or when one object will receive events from many sources.
  • With either, remember the ownership direction. A closure that captures self strongly and is stored on an object that self owns is also a retain cycle; use [weak self] as shown in Escaping Closures and Autoclosures.

In modern Swift you will also see async functions and AsyncStream replace many delegates; see Introduction to Swift Concurrency.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does func save(_ item: Codable & CustomStringConvertible) require of its argument?

    The ampersand builds a composition: a value must satisfy every listed protocol.
  2. 2. Why is a delegate property usually declared weak?

    The delegate often owns the object that holds it. A strong reference in both directions would keep both alive forever.
  3. 3. Which declaration lets a property of that protocol type be marked weak?

    Only class-bound protocols can be used with weak, and : AnyObject makes a protocol class-bound.
  4. 4. How do you make some delegate methods optional in pure Swift?

    Pure Swift protocols have no optional requirements; default implementations let a conforming type skip methods it does not need.
  5. 5. Does typealias Both = A & B create a new protocol you can extend?

    A typealias is just a name for the requirement. A real protocol such as protocol Both: A, B {} can have extensions.

Summary

  • A & B is a composition: the value must conform to every protocol listed, and the composition can mention a class or AnyObject.
  • Use a typealias to name a composition; use protocol inheritance when you need a real protocol you can extend.
  • The delegate pattern passes decisions and events to an object that conforms to a protocol, keeping the owner reusable.
  • Delegate methods start with the sender, and names with will/did report events while should asks questions.
  • Declare delegate protocols : AnyObject and hold delegates weak to avoid retain cycles.
  • Pure Swift has no optional protocol methods: use default implementations in an extension, and declare the methods in the protocol so they dispatch dynamically.
  • Prefer a closure for a single callback and a delegate for several related ones.

Next: Associated Types