Jared
Jared

Reputation: 4810

How can I specify a CollectionType for a generic struct/class?

For example, say I have an struct AdjacencyList where I want to specify the type of container that the vertices are stored in such that the user can choose Set if they don't want duplicates, or Array if they do.

(I've omitted protocol conformances for the types since my example code is already incorrect as-is and many would have to be conformed to depending on the container type. For example, Set elements would need to be Hashable.)

public struct AdjacencyList<VertexType, EdgeType, VertexContainerType, EdgeContainerType> {
    var vertices: VertexContainerType<VertexType>
    ...
}

Upvotes: 0

Views: 77

Answers (1)

Matthew Seaman
Matthew Seaman

Reputation: 8092

The issue you are running into is that CollectionType is not generic. One way around the specific issue you point out is to just have the client specify the container types and then you can extract the actual element types.

For example:

struct AdjacencyList<VertexContainerType: CollectionType, EdgeContainerType: CollectionType> {

    var vertices: VertexContainerType

    typealias VertexType = VertexContainerType.Generator.Element

    typealias EdgeType = EdgeContainerType.Generator.Element

    func printTypes() {
        print("VertexType: \(VertexType.self)\nEdgeType: \(EdgeType.self)")

    }

}

let a = AdjacencyList<Array<Int>, Array<Double>>(vertices: [Int]())

a.printTypes()

// Prints:
// VertexType: Int
// EdgeType: Double

Upvotes: 1

Related Questions