Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 146 ยท Protocols and Generics

Protocols

Learn Swift protocols - declaring requirements, conforming with structs, classes and enums, protocols as types, mutating and static requirements, initializers, inheritance and default implementations.

A protocol is a list of requirements: "any type that wants to be a Drawable must have a draw() method". The protocol says what a type can do and nothing about how. Any struct, class or enum can promise to meet the list, and then code that only needs a Drawable can work with all of them without knowing which one it has.

Protocols are the center of Swift's design. The standard library is built on them (Equatable, Hashable, Sequence, Codable...), and Swift's guidance for writing flexible code is "protocol-oriented": describe behavior with protocols, share implementations with extensions, and keep the data in value types. This lesson teaches the fundamentals; the lessons that follow add protocol extensions, composition and delegation, associated types and generics.

Declaring a protocol and conforming to it

A protocol lists requirements without bodies. A type conforms by naming the protocol after its own name and supplying every requirement.

Swift A first 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.

Car and Garden have nothing in common except that both meet Describable. The array holds both, and the loop calls describe() on each; Swift picks the right implementation. The { get } after summary means "readable"; a conforming type may supply a stored property, a constant or a computed property.

The any keyword marks Describable as an existential: "some value of unknown type that conforms". You will meet it again in Opaque and Existential Types. Writing any is always allowed and is the recommended style; the compiler requires it when the protocol has associated types or Self requirements, and the stricter ExistentialAny language feature makes it mandatory everywhere.

What a protocol can require

A protocol can ask for four kinds of members:

  • Properties, with { get } (readable) or { get set } (readable and writable). A protocol never says whether the property is stored or computed.
  • Methods, written without bodies. Mark a requirement mutating if value types need to change self.
  • Initializers, so generic code can create instances.
  • Static members, for type-level requirements.
Swift Property, method, initializer and static requirements

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 generic function makeAndReset never mentions Counter: it creates an instance through the init(value:) requirement, reads the label, and calls the mutating method. It prints counter starts at 41 and then now 0. The <T: Resettable> syntax is a generic constraint and is covered in Generics.

Mutating requirements

A method that changes a struct must be declared mutating in the protocol. Classes may implement a mutating requirement without writing the keyword, because a class method can always change its properties. Leave mutating out of the protocol and structs cannot change themselves through it.

Conforming with extensions

You can add conformance later, in an extension, even to types you did not write. Putting the conformance in its own extension is also a neat way to organize code.

Swift Retroactive conformance

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 and Int are types from the standard library, yet they now conform to your protocol. This is powerful, and it is also why public libraries must be careful: if two modules both add the same conformance to the same type, programs break. Inside your own project it is perfectly safe.

Protocols are types, and errors are helpful

When you try to meet a protocol but forget a requirement, the compiler lists exactly what is missing:

Swift Missing requirement (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:6:8: error: type 'Song' does not conform to protocol 'Playable' with the note protocol requires function 'stop()' with type '() -> ()' pointing at the missing method, and a second note, add stubs for conformance, offering a fix-it. Swift will never let a conformance be only partial.

Class-only protocols

Writing : AnyObject after the protocol name limits it to classes. You need that when the protocol's values must be held weakly or compared by identity, as in the delegate pattern from Protocol Composition and Delegation.

Swift
protocol Observer: AnyObject {
    func didChange()
}

This snippet is read-only; it only declares a protocol.

Default implementations

A protocol on its own cannot contain method bodies. But an extension of the protocol can provide a default body, so conforming types get the behavior for free and may override it.

Swift Default implementation in a protocol extension

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.

Friendly implements only name; greet() is inherited from the extension. Formal supplies its own and wins. The next lesson, Protocol Extensions, explains the dispatch rules that decide which version runs in more complicated cases.

Protocol inheritance

A protocol can inherit from one or more others. A type that conforms to the child must satisfy every parent requirement as well.

Swift A protocol that inherits

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.

A Student is a Person, a Named and an Aged all at once, so it can be passed to report(on:), which accepts anything Named. The some Named parameter is shorthand for a generic constraint; see Opaque and Existential Types.

Protocols you already use

Many of the types in earlier lessons were protocol conformances in disguise: Equatable, Hashable and Comparable (Equatable, Hashable and Comparable), Codable (Codable), CustomStringConvertible (CustomStringConvertible and Debug Output), Sequence and Collection (Collection Protocols). Learning to read the list after the colon on a type declaration tells you most of what the type can do.

Design guidance

  • Name by role. Use -able/-ible for capabilities (Drawable), nouns for things (Collection, Delegate), and a Protocol suffix only to avoid a clash.
  • Keep protocols small. Several small protocols that can be combined (see composition) beat one big one.
  • Do not start with a protocol. Write concrete types first. Add a protocol when a second type needs to be used in the same place, or when you need a seam for testing.
  • Prefer value types. Structs and enums conform just as well as classes, without shared mutable state.
  • Avoid existentials in hot code. any P boxes its value and uses dynamic dispatch. Generics (<T: P>) and some P let the compiler specialize.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a protocol contain?

    A protocol declares requirements (properties, methods, initializers, static members). Types supply the implementation.
  2. 2. What does { get set } after a property in a protocol mean?

    get set means readable and writable. The conforming type decides whether to use a stored or computed property.
  3. 3. How do you provide a default method body for every conforming type?

    Protocol declarations hold no bodies. A protocol extension supplies default implementations.
  4. 4. Why mark a protocol method mutating?

    Structs and enums need mutating to change self; the protocol must allow it.
  5. 5. What does protocol Delegate: AnyObject do?

    AnyObject limits the protocol to class types, which enables weak references and identity comparison.

Summary

  • A protocol declares requirements: properties ({ get } or { get set }), methods, initializers and static members.
  • Structs, classes and enums conform by providing every requirement; the compiler reports what is missing.
  • Protocols are types: use any Protocol for values of unknown concrete type, or generics and some for performance.
  • Mark requirements mutating when value types should be able to change themselves.
  • Extensions can add conformance retroactively and can supply default implementations.
  • Protocols can inherit from other protocols, and AnyObject restricts them to classes.

Next: Protocol Extensions