要件定義し、CollectionType
に準拠:そうのようにそれを実装することで、この要件
/// Returns the element at the given `position`.
public subscript (position: Self.Index) -> Self.Generator.Element { get }
Array
満足する:
public struct Array<Element> : CollectionType, MutableCollectionType, _DestructorSafeContainer {
// ...
// Swift can infer that Self.Index == Int & Self.Generator.Element == Element
public subscript (index: Int) -> Element
// ...
}
これにより、Swift t o Array
の汎用プレースホルダータイプElement
が関連タイプSelf.Generator.Element
を満たすために使用され、具体的タイプInt
が関連タイプSelf.Index
を満たすために使用されているとします。
これは、そのプロトコルに準拠した特定のタイプのプロトコル要件の実装で使用されるタイプによって、関連するタイプが暗黙的に満たされるという事実を利用しています。たとえば、あなたのケースで:
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
}
associatedtype
を使用するいかなるプロトコル要件が存在しない場合はもちろん、それはtypealias
と明示的に満足する必要がありますが:
protocol Animal {
associatedtype Breed
}
struct Dog<T> : Animal{
typealias Breed = T
}