當(dāng)protocol中帶有associatedtype或者Self約束時(shí)豌汇,這個(gè)協(xié)議就不能被當(dāng)作一個(gè)獨(dú)立的類型使用了勾习,例如:
在沒有這些約束的時(shí)候轧坎,我們可以這樣寫:
protocol Food {}
protocol Animal {
func eat(_ food: Food)
}
func isDangerous(animal: Animal) -> Bool {
if animal is Tiger {
return true
}
return false
}
但是如果給Animal添加了associatedtype
protocol Animal {
associatedtype F: Food
func eat(_ food: F)
}
此時(shí)在寫出上面isDangerous的代碼時(shí)股耽,回報(bào)錯(cuò)
protocol 'Animal' can only be used as a generic constraint because it has Selfor associated type requirements
這是因?yàn)?Swift 需要在編譯時(shí)確定所有類型蹄咖,這里因?yàn)锳nimal包含了一個(gè)不確定的類型褐健,所以隨著Animal本身類型的變化,其中的F將無法確定 (試想一下如果在這個(gè)函數(shù)內(nèi)部調(diào)用eat的情形澜汤,你將無法指定eat參數(shù)的類型)蚜迅。在一個(gè)協(xié)議加入了像是associatedtype或者Self的約束 后,它將只能被用為泛型約束俊抵,而不能作為獨(dú)立類型的占位使用谁不,也失去了動(dòng)態(tài)派發(fā)的特性。也 就是說徽诲,這種情況下刹帕,我們需要將函數(shù)改寫為泛型:
func isDangerous<T: Animal>(animal: T) -> Bool {
if animal is Tiger {
return true
}
return false
}