发布于 2015-06-14 01:55:41 | 176 次阅读 | 评论: 0 | 来源: 网络整理
协议类型可以被集合使用,表示集合中的元素均为协议类型:
let things: TextRepresentable[] = [game,d12,simoTheHamster]
如下所示,things数组可以被直接遍历,并调用其中元素的asText()函数:
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被当做是TextRepresentable类型而不是Dice,DiceGame,Hamster等类型。因此能且仅能调用asText方法