简体   繁体   English

如何使用协议和where子句扩展CollectionType?

[英]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: 我想使用该协议扩展CollectionType,其中元素是特定类型:

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

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 : Swift Evolution邮件列表中讨论了此功能,从[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 { } 扩展Array:Equatable其中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 . 但是据我所见,它在Swift 2中不可用,并且-在我目前所见的情况下-不在https://github.com/apple/swift-evolution上有关Swift 3的最新提议列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM