Instruction 1

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

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.

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.

protocol MediaItem {
    var title: String { get }
    var price: Double { get set }
}
// 1
protocol MediaCollection {
    // 2
    associatedtype Item: MediaItem
    // 3
    var items: [Item] { get set }
    // 4
    func getDescription() -> String
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo 1