プロトコルは、Protocols as Types で触れているように、配列や辞書のようなコレクションに保管される型として使用することができます。この例では、TextRepresentable な何かの配列を生成しています。

let things: [TextRepresentable] = [game, d12, simonTheHamster]

配列内のアイテムを繰り返し処理し、各アイテムのテキストの説明を出力することができます。

for thing in things {
    print(thing.textualDescription)
}
// A game of Snakes and Ladders with 25 squares
// A 12-sided dice
// A hamster named Simon

定数 thing が TextRepresentable 型であることに注目してください。実際のインスタンスは次の型のいずれかであるにもかかわらず、Dice 型でも、DiceGame 型でも、Hamster 型でもありません。それでもやはり、TextRepresentable 型で、かつ TextRepresentable な何かには textualDescription プロパティがあることがわかっているため、ループの各回で thing.textualDescription に安全にアクセスすることができています。


Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.