2016-09-24 8 views
3

Swift 2.3でArrayはElement関連型をどこで定義していますか?ArrayはElement関連型をどこで定義していますか?

要素が関連付けられた型を持つGeneratorTypeを実装するため、定義する必要があります。 ディクショナリとセットはどちらもElementを定義しますが、Arrayはそれをどこで定義していますか?

ArrayにはElementというジェネリックタイプがありますが、ジェネレータタイプがGeneratorTypeプロトコルを満たしていますか?

私はこれを遊び場で試してみましたが、うまくいかなかったのです。スイフト2、Array

例えば

protocol Animal{ 
    associatedtype Breed 
} 

struct Dog<Breed>: Animal{ 

} 

答えて

0

要件定義し、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 
} 
関連する問題