2016-09-24 3 views
3

Dans Swift 2.3, où Array définit-il le type associé à l'élément?Où Array définit-il le type associé à l'élément?

Il doit le définir car il implémente GeneratorType qui a Element un type associé. Dictionary et Set définissent tous les deux Element mais où Array le définit-il?

Array a un type générique appelé Element, est-ce qu'un type générique satisfait le protocole GeneratorType?

Je l'ai essayé dans la cour de récréation et ça ne marche pas pour moi.

Par exemple

protocol Animal{ 
    associatedtype Breed 
} 

struct Dog<Breed>: Animal{ 

} 

Répondre

0

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 
}