-
Embrace Swift generics
Generics are a fundamental tool for writing abstract code in Swift. Learn how you can identify opportunities for abstraction as your code evolves, evaluate strategies for writing one piece of code with many behaviors, and discover language features in Swift 5.7 that can help you make generic code easier to write and understand.
Ressources
Vidéos connexes
WWDC23
WWDC22
-
Rechercher dans cette vidéo…
-
-
27:10 - Complete example
protocol AnimalFeed { associatedtype CropType: Crop where CropType.Feed == Self static func grow() -> CropType } protocol Crop { associatedtype Feed: AnimalFeed where Feed.CropType == Self func harvest() -> Feed } protocol Animal { associatedtype Feed: AnimalFeed func eat(_ food: Feed) } struct Farm { func feed(_ animal: some Animal) { let crop = type(of: animal).Feed.grow() let produce = crop.harvest() animal.eat(produce) } func feedAll(_ animals: [any Animal]) { for animal in animals { feed(animal) } } } struct Cow: Animal { func eat(_ food: Hay) {} } struct Hay: AnimalFeed { static func grow() -> Alfalfa { Alfalfa() } } struct Alfalfa: Crop { func harvest() -> Hay { Hay() } }
-