Generic Composition and Opaque Types
Generic data structures can compose with one another using protocols to build systems of types that elegantly describe more complex ideas.
For example, think of an array of dictionaries, which might have a composed type like Array<Dictionary<String,Int>>
.
Sometimes, you might want to hide some of the gritty implementation details of your compositions.
To see what this looks like in practice, you will model a hungry human ordering toast at a restaurant.
Begin with a Food
protocol and a food that conforms to it.
... protocol Food { var menuListing: String { get } } struct Bread: Food { var kind = "sourdough" var menuListing: String { "\(kind) bread" } }
Using a protocol to ...
Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.