扩展集合类型时的计算元素类型



>我正在尝试实现一个符合/扩展CollectionType的协议,但是它不需要一个显然是元素类型的通用类型,所以我希望能够计算/强制Generator.Element的类型。

我将使用映射协议作为示例:

protocol Map : CollectionType {
    typealias Key
    typealias Value
    subscript(key:Key) -> Value? { get }
}

有没有办法指定Self.Generator.Element必须(Key, Value),而不是类型作者的文档?

您希望定义一个CollectionType的子协议CollectionType.Generator.Element嵌套类型具有附加约束。这个嵌套类型属于CollectionType.Generator嵌套类型,它被约束为GeneratorType,所以首先我们需要引入一个具有附加约束的GeneratorType子协议:

protocol KeyValueGeneratorType: GeneratorType {
    associatedtype Key
    associatedtype Value
    mutating func next() -> (Key, Value)?
}

然后我们可以引入一个具有附加约束的CollectionType子协议:

protocol KeyValueCollectionType: CollectionType {
    associatedtype Generator: KeyValueGeneratorType
}

Dictionary类型实际上确实符合我们的协议,因此我们只需要一个简短的声明来表明这一点:

extension DictionaryGenerator: KeyValueGeneratorType {}
extension Dictionary: KeyValueCollectionType {}

您必须创建要符合的生成器元素的类型。例如。

protocol SpecialElement {
    typealias key : Int { get }
    typealias Value : Int { get }
}

然后:

extension CollectionType where Self.Generator.Element: SpecialElement {
      func addValues() -> Int {
         var total = 0
         for item in self {
           total += item.Value
         }
      return total       
     }
}

最新更新