associatedtype用于protocol中 associatedtype類型是在protocol中?代指一個確定類型并要求該類型實現(xiàn)指定方法
比如 我們定義一個protocol
protocol Container {
associatedtype ItemType
mutating func append(_ item:ItemType)
var count:Int {
get
}
subscript(i:Int) -> ItemType {
get
}
}
之后實現(xiàn)這個協(xié)議
struct IntStack: Container {
// original IntStack implementation
var items = [Int]()
mutating func push(_ item:Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
// conformance to the Container protocol
typealias ItemType = Int
mutating func append(_ item:Int) {
self.push(item)
}
var count:Int {
return items.count
}
subscript(i:Int) -> Int {
return items[i]
}
}
其中items實現(xiàn)了ItemType這個代指變量
由于swift的類型推斷,你實際上并不需要聲明一個具體ItemType的Int作為定義的一部分IntStack罢低。由于IntStack符合所有的要求Container協(xié)議唐责,swift可以推斷出適當?shù)腎temType使用柿汛,只需通過查看類型append(_:)方法的item參數(shù)和標的返回類型厢岂。事實上樟遣,如果你刪除typealias ItemType = Int上面從代碼行茧妒,一切仍然有效酬蹋,因為很明顯應該使用什么類型ItemType及老。