Applying Protocol-Oriented Programming in Development

Oct 17 2023 · Swift 5.9, iOS 17, Xcode 15

Lesson 02: Protocol Design & Composition

Demo 1

Episode complete

Play next episode

Next
Transcript

Demo

Now, it’s time to see how to implement a MediaCollection. Open the starter project playground for this lesson in Xcode. MediaItem and MediaCollection are already defined for you.

A few media types have also been defined for you, such as Movie, TVShow and VideoGame. These all conform to MediaItem and have a title and a price property. Some also have an additional duration, where appropriate. There’s also a CardGame for you to use later in the lesson.

First, create a collection for your movies:

struct MovieCollection: MediaCollection {

}

This collection will contain Movies as the Item. To satisfy the compiler, use typealias to define the associated type:

typealias Item = Movie

Then, define the array of items:

var items: [Movie] = []

Finally, implement getDescription():

func getDescription() -> String {
    "The movie collection contains \(items.count) movies"
}

Because you specify the type of Item in the items array, you can even remove the type alias; the compiler will infer it for you.

[Remove type alias and show working]

Most of the time, you want to keep the type alias, however, so your code is more readable.

[Undo the change]

Finally, create a couple of movies and add them to the collection, then print the description:

let bourneIdentity = Movie(title: "The Bourne Identity", price: 3.99, duration: 113)
let oppenheimer = Movie(title: "Oppenheimer", price: 17.99, duration: 180)

var movieCollection = MovieCollection()
movieCollection.items.append(bourneIdentity)
movieCollection.items.append(oppenheimer)

print(movieCollection.getDescription())

In this demo, you implemented a MovieCollection conforming to the MediaCollection protocol, demonstrating the practical application of associated types. Here are the steps you followed:

  • First, you defined the MovieCollection struct to represent a collection of movies, specifying Movie as the associated Item type using a typealias.
  • Then, you created an array of Movie items to hold the collection’s content.
  • Finally, you implemented the getDescription() function, which counts the movies in the collection and returns a descriptive message.

This demo showcases how associated types allow you to work with generic data types while preserving the safety and structure of protocols.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction 1 Next: Instruction 2