Swift 2, Array
est conforme à CollectionType
, qui définit l'exigence:
/// Returns the element at the given `position`.
public subscript (position: Self.Index) -> Self.Generator.Element { get }
Array
satisfait cette exigence en mettant en œuvre comme si:
public struct Array<Element> : CollectionType, MutableCollectionType, _DestructorSafeContainer {
// ...
// Swift can infer that Self.Index == Int & Self.Generator.Element == Element
public subscript (index: Int) -> Element
// ...
}
Cela permet t Swift o en déduire que placeholder générique de type Element
est utilisé pour satisfaire le type associé Self.Generator.Element
, et le type concret Int
est utilisé pour satisfaire le type associé Self.Index
. Cela profite du fait que les types associés peuvent être satisfaits implicitement par le type utilisé dans l'implémentation d'une exigence de protocole dans un type donné conforme à ce protocole. Par exemple, dans votre cas:
protocol Animal {
associatedtype Breed
var breed : Breed { get }
}
// I've named the generic placeholder T to simply make clear that Swift is inferring
// T == Breed and therefore satisfying the associatedtype requirement.
// You can rename the generic placeholder back to 'Breed' – the compiler will still
// infer that it's satisfying the Breed associatedtype.
struct Dog<T> : Animal{
let breed : T
}
enum BreedOfCat {/* ... */}
struct Cat : Animal {
// same principle with non-generic types: BreedOfCat == Breed
let breed : BreedOfCat
}
Bien sûr, s'il n'y a pas aux exigences du protocole qui utilisent le associatedtype
, il va falloir se contenter explicitement une typealias
:
protocol Animal {
associatedtype Breed
}
struct Dog<T> : Animal{
typealias Breed = T
}