Instruction 1

Protocol Design

When designing your protocols, you should consider how you want to use the types that conform to that protocol. One of the great things about protocols is that you can conform a type to multiple protocols. This allows you to keep your protocols narrow in scope and design them only for that particular use case.

Conforming to protocols is not only limited to classes, either. You can conform structs and even enums to protocols as well. This allows you to use the best type for the job and choose between value and reference semantics where it makes sense.

Associated Types

When creating a protocol, you might encounter scenarios where you don’t know which specific type will be used in the protocol. To accommodate this, you’ll want to keep the protocol generic and allow the implementers to use different types. This is where associated types come into play.

To provide a generic type in a protocol, you use an associated type — a placeholder for a type that will be provided by the implementer. You can then use this type in your protocol as if it were a real type.

A classic example of when to use an associated type is a protocol that contains some sort of collection. You don’t want to enforce what you’re going to collect, but you need a way to represent and refer to that type.

For example, imagine you’re building an app to catalog all the media in your house. First, you might define a protocol for a MediaItem:

protocol MediaItem {
    var title: String { get }
    var price: Double { get set }
}

This protocol defines two properties: a read-only title and a mutable price. You could use this to represent anything from books to movies to video games. Then, you can define a protocol for a MediaCollection:

// 1
protocol MediaCollection {
    // 2
    associatedtype Item: MediaItem
    // 3
    var items: [Item] { get set }
    // 4
    func getDescription() -> String
}

This code defines the following:

  1. A protocol called MediaCollection that represents a collection of similar media items, such as a collection of movies.
  2. An associated type, Item, for the protocol to use. Ensure that Item conforms to MediaItem so that any implementer of MediaCollection’s can use the API defined in MediaItem.
  3. An array of Items called items, which the collection will contain. This is where you use the associated type; it allows you to leave the type in the array unspecified until a type conforms to the protocol.
  4. A simple function, getDescription(), which returns a string.

Now that you’ve learned about associated types, you’ll explore a practical demonstration that puts this knowledge into action.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo 1