Nuno Dias
Nuno Dias

Reputation: 3948

How to extend a CollectionType with a Protocol and a where clause?

I have this protocol definition:

protocol BarChartDataConvertible {
    var barChartData: BarChartData { get }
}

And I would like to extend a CollectionType where the elements are of a specific type, with that protocol:

extension CollectionType where Generator.Element == DataPoint {

    // This works, by I also want it to be enforced by the BarChartDataConvertible
    // var barChartData: BarChartData { ... }

}

How can I do this?

[DataPoint(), DataPoint()].barChartData

Upvotes: 0

Views: 381

Answers (1)

Martin R
Martin R

Reputation: 539795

You can define extension methods which apply only to a restricted type of the generic placeholders

extension CollectionType where Generator.Element == DataPoint {
    var barChartData: BarChartData { return somethingUseful }
}

and then

[DataPoint(), DataPoint()].barChartData

compiles. But you cannot declare a "conditional conformance to a protocol", such as

extension CollectionType: DataPoint where Generator.Element == DataPoint { ... }

Such a feature is discussed on the Swift Evolution mailing list, starting at [swift-evolution] [Manifesto] Completing Generics:

*Conditional conformances

Conditional conformances express the notion that a generic type will conform to a particular protocol only under certain circumstances. For example, Array is Equatable only when its elements are Equatable:

extension Array : Equatable where Element : Equatable { }

but it is not available in Swift 2 and – as far as I can see – not on the current lists of proposals for Swift 3 at https://github.com/apple/swift-evolution.

Upvotes: 1

Related Questions