Applying Protocol-Oriented Programming in Development

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

Lesson 02: Protocol Design & Composition

Demo 3

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 the playground in Xcode. First, define a new protocol called RandomEntertainmentPicker to help you pick what to do this evening:

protocol RandomEntertainmentPicker {
    associatedtype Item
    func getItemToEnjoy() -> Item?
}
struct MediaShelf<T: MediaItem>: MediaCollection, RandomEntertainmentPicker {
    var items: [T] = []
    
    func getItemToEnjoy() -> T? {
        items.randomElement()
    }
}
print("Let's play \(videoGameShelf.getItemToEnjoy()?.title ?? "Nothing!")")
func printItemDetails(_ item: MediaItem & Codable) throws {
    let jsonEncoder = JSONEncoder()
    let data = try jsonEncoder.encode(item)
    if let string = String(data: data, encoding: .utf8) {
        print(string)
    }
}
try printItemDetails(catan)
try printItemDetails(noTimeToDie)
struct CardGames: RandomEntertainmentPicker {
    let games: [CardGame]
    
    func getItemToEnjoy() -> CardGame? {
        return games.randomElement()
    }
}
let bridge = CardGame(title: "Bridge")
let solitaire = CardGame(title: "Solitaire")

let cardGames = CardGames(games: [bridge, solitaire])
guard let cardGameToPlay = cardGames.getItemToEnjoy() else {
    fatalError("We have no card games!")
}
print("We have some cards so we'll play \(cardGameToPlay.title)")
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction 3 Next: Conclusion