Applying Protocol-Oriented Programming in Development

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

Lesson 02: Protocol Design & Composition

Demo 2

Episode complete

Play next episode

Next

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

Demo

Head back to Xcode to see how this works. First, create an extension on MediaCollection:

extension MediaCollection {

}
mutating func add(_ item: Item) {
    self.items.append(item)
}
movieCollection.add(bourneIdentity)
movieCollection.add(oppenheimer)
func getDescription() -> String {
    "Collection contains \(items.count) items"
}
struct MediaShelf: MediaCollection {

}
var items: [T] = []
struct MediaShelf<T: MediaItem>: MediaCollection
let catan = BoardGame(title: "Catan", price: 40)
let arkhamKnight = VideoGame(title: "Batman: Arkham Knight", price: 49.99, console: .xbox)
let tearsOfTheKingdom = VideoGame(title: "The Legend of Zelda: Tears of the Kingdom", price: 59.99, console: .switch)
let noTimeToDie = Movie(title: "No Time To Die", price: 19.99, duration: 163)

var boardGameShelf = MediaShelf<BoardGame>()
var movieShelf = MediaShelf<Movie>()
var videoGameShelf = MediaShelf<VideoGame>()
boardGameShelf.add(catan)
movieShelf.add(noTimeToDie)
videoGameShelf.add(arkhamKnight)
videoGameShelf.add(tearsOfTheKingdom)

print(boardGameShelf.getDescription())
print(movieShelf.getDescription())
print(videoGameShelf.getDescription())
extension MediaShelf where T == VideoGame {
    func getDescription() -> String {
        let xboxCount = items.filter({ $0.console == .xbox }).count
        let playstationCount = items.filter({ $0.console == .playstation }).count
        let switchCount = items.filter({ $0.console == .switch }).count
        return "This collection contains \(xboxCount) Xbox games, \(playstationCount) Playstation games and \(switchCount) Switch games"
    }
}
extension MediaShelf where T: Codable {
    func printItems() throws {
        let jsonEncoder = JSONEncoder()
        let data = try jsonEncoder.encode(items)
        if let string = String(data: data, encoding: .utf8) {
            print(string)
        }
    }
}
struct BoardGame: MediaItem, Codable
try boardGameShelf.printItems()
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction 2 Next: Instruction 3