Instruction 1

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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