從字面上來理解,就是相關(guān)類型。意思也就是被
associatedtype
關(guān)鍵字修飾的變量,相當(dāng)于一個占位符,而不能表示具體的類型。具體的類型需要讓實現(xiàn)的類來指定。
protocol Food { }
protocol Animal {
func eat(_ food: Food)
}
struct Meat: Food { }
struct Lion: Animal {
func eat(_ food: Food) {
if let meat = food as? Meat {
print("eat \(meat)")
} else {
fatalError("Tiger can only eat meat!")
}
}
}
let meat = Meat()
Lion().eat(meat)
在實現(xiàn)中的轉(zhuǎn)換很多時候并沒有太多的意義,而且將責(zé)任扔給了運行時。好的做法是讓編譯的時候就確定Food
的類型,這種情況就可以用associatedtype
。
protocol Food {}
protocol Animal {
associatedtype F: Food
func eat(_ food: F)
}
struct Meat: Food {}
struct Lion: Animal {
func eat(_ food: Meat) {
print("eat \(food)")
}
}
let meat = Meat()
Lion().eat(meat)
不過在添加 associatedtype 后,Animal 協(xié)議就不能被當(dāng)作獨立的類型使用了。這時候就需要使用泛型。
func isDangerous<T: Animal>(animal: T) -> Bool {
if animal is Lion {
return true
} else {
return false
}
}