即便無法修改源代碼,依然可以通過擴(kuò)展(Extension)來擴(kuò)充已存在類型(譯者注: 類,結(jié)構(gòu)體,枚舉等)。擴(kuò)展可以為已存在的類型添加屬性,方法,下標(biāo),協(xié)議等成員。詳情請(qǐng)?jiān)?a target="_blank" style="box-sizing: border-box; -webkit-tap-highlight-color: transparent; -webkit-font-smoothing: antialiased; color: rgb(65, 131, 196); text-decoration: none;" target="_blank">擴(kuò)展章節(jié)中查看。
注意: 通過擴(kuò)展為已存在的類型遵循協(xié)議時(shí),該類型的所有實(shí)例也會(huì)隨之添加協(xié)議中的方法。
TextRepresentable協(xié)議含有一個(gè)asText,如下所示:
protocol TextRepresentable {
func asText() -> String
}
通過擴(kuò)展為上一節(jié)中提到的Dice類遵循TextRepresentable協(xié)議
extension Dice: TextRepresentable {
cun asText() -> String {
return "A \(sides)-sided dice"
}
}
從現(xiàn)在起,Dice類型的實(shí)例可被當(dāng)作TextRepresentable類型:
let d12 = Dice(sides: 12,generator: LinearCongruentialGenerator())
println(d12.asText())
// 輸出 "A 12-sided dice"
SnakesAndLadders類也可以通過擴(kuò)展的方式來遵循協(xié)議:
extension SnakeAndLadders: TextRepresentable {
func asText() -> String {
return "A game of Snakes and Ladders with \(finalSquare) squares"
}
}
println(game.asText())
// 輸出 "A game of Snakes and Ladders with 25 squares"