協(xié)議類型可以被集合使用,表示集合中的元素均為協(xié)議類型:
let things: TextRepresentable[] = [game,d12,simoTheHamster]
如下所示,things數(shù)組可以被直接遍歷,并調(diào)用其中元素的asText()函數(shù):
for thing in things {
println(thing.asText())
}
// A game of Snakes and Ladders with 25 squares
// A 12-sided dice
// A hamster named Simon
thing被當(dāng)做是TextRepresentable類型而不是Dice,DiceGame,Hamster等類型。因此能且僅能調(diào)用asText方法