迭代器返回通用集合-Swift 4.2

时间:2018-11-06 22:04:34

标签: swift generics collections iterator

我可以编写以下迭代器:

enum Stage { case a, ab, end }

struct SetMaker<Input: Hashable>: Sequence, IteratorProtocol {
  var a,b: Input
  var stage = Stage.a

  init(a: Input, b: Input) {
    self.a = a
    self.b = b
  }

  mutating func next() -> Set<Input>? {
    switch stage {
    case .a:    stage = .ab;   return Set<Input>([a])
    case .ab:   stage = .end;  return Set<Input>([a,b])
    case .end:                 return nil
    }
  }
}

let setMaker = SetMaker(a: "A", b: "B")
for x in setMaker {
  print(x)
}

struct ArrayMaker<Input: Hashable>: Sequence, IteratorProtocol {
  var a: Input
  var b: Input
  var stage = Stage.a

  init(a: Input, b: Input) {
    self.a = a
    self.b = b
  }

  mutating func next() -> Array<Input>? {
    switch stage {
    case .a:    stage = .ab;   return Array<Input>([a])
    case .ab:   stage = .end;  return Array<Input>([a,b])
    case .end:                 return nil
    }
  }
}

let arrayMaker = ArrayMaker(a: "A", b: "B")
for x in arrayMaker {
  print(x)
}

第一个返回Set序列,第二个返回Arrays序列。

这两种方法都可以正常工作,但是我想保留我的代码“ DRY”(即,不要重复自己)。

所以我想写一些泛型的东西,以允许任何一个的构造。 我的尝试是:

struct AnyMaker<Input: Hashable, CollectionType>: Sequence, IteratorProtocol {
  var a,b: Input
  var stage = Stage.a

  init(a: Input, b: Input) {
    self.a = a
    self.b = b
  }

  mutating func next() -> CollectionType<Input>? {
    switch stage {
    case .a:    stage = .ab;   return CollectionType<Input>([a])
    case .ab:   stage = .end;  return CollectionType<Input>([a,b])
    case .end:                 return nil
    }
  }
}

但这无法编译。 任何帮助表示赞赏:-)

编辑...

@Rob提出了一个很好的建议,这使我有所作为-请参阅他的答案。 但是,如果有时我想让集合成为集合,则会出现问题,因为集合不是RangeReplaceable。

换句话说,我创建了一些稍有不同的代码:

struct Pairs<C>: Sequence, IteratorProtocol
where C: RangeReplaceableCollection {

  var collection: C
  var index: C.Index

  init(_ collection: C) {
    self.collection = collection
    index = self.collection.startIndex
  }

  mutating func next() -> C? {
    guard index < collection.endIndex else { return nil }
    let element1 = collection[index]
    index = collection.index(after: index)
    guard index < collection.endIndex else { return nil }
    let element2 = collection[index]
    let pair = [element1,element2]
    return C(pair)
  }
}

do {
  print("Pairs from array")
  let array = ["A","B","C"]
  let pairs = Pairs(array) //This line is fine
  for pair in pairs {
    print(pair)
  }
}

do {
  print("Pairs from set")
  let set = Set(["A","B","C"])
  let pairs = Pairs(set) // This line causes error
  for pair in pairs {
    print(pair)
  }
}

“ let pair = Pairs(set)”行产生错误: “参数类型'Set'与预期类型'RangeReplaceableCollection'不符”

所以我需要弄清楚如何在不使用RangeReplaceableCollection的情况下实例化集合?

2 个答案:

答案 0 :(得分:1)

您从未限制CollectionType的类型,因此Swift根本不知道您可以创建一个,更不用说通过传递数组来创建一个了。 Collection本身也不承诺任何init方法。我们需要转到RangeReplaceableCollection来获取该信息:

struct AnyMaker<CollectionType>: Sequence, IteratorProtocol
where CollectionType: RangeReplaceableCollection {
    typealias Input = CollectionType.Element

    ...
}

完成此操作后,next()如下所示:

mutating func next() -> CollectionType? {
    switch stage {
    case .a:    stage = .ab;   return CollectionType([a])
    case .ab:   stage = .end;  return CollectionType([a,b])
    case .end:                 return nil
    }
}

请注意,这将返回CollectionType?而不是CollectionType<Input>?CollectionType的任何要求都不需要带有类型参数,因此我们不能传递一个。即使我们想要,也无法表达“采用类型参数”,但是我们不想要它。 CollectionType只需拥有一些Element,而RangeReplaceableCollection承诺了这一点。

let anyMaker = AnyMaker<[String]>(a: "A", b: "B")
for x in arrayMaker {
    print(x)
}

完整代码:

struct AnyMaker<CollectionType>: Sequence, IteratorProtocol
where CollectionType: RangeReplaceableCollection {
    typealias Input = CollectionType.Element
    var a,b: Input
    var stage = Stage.a

    init(a: Input, b: Input) {
        self.a = a
        self.b = b
    }

    mutating func next() -> CollectionType? {
        switch stage {
        case .a:    stage = .ab;   return CollectionType([a])
        case .ab:   stage = .end;  return CollectionType([a,b])
        case .end:                 return nil
        }
    }
}

答案 1 :(得分:1)

即使Collection不需要初始化程序,但Array和Set确实具有我们想要的初始化程序:

init<S : Sequence>(_ elements: S) where S.Element == Element

因此,通过创建一个需要此协议的新协议,然后使用该协议扩展Array和Set,我们可以假定UsableCollections将具有此初始化程序,并按要求完成所有工作:

protocol UsableCollection: Collection {
  init<S : Sequence>(_ elements: S) where S.Element == Element
}

extension Array: UsableCollection { }
extension Set: UsableCollection { }

struct Pairs<C: UsableCollection>: Sequence, IteratorProtocol {
  var collection: C
  var index: C.Index

  init(_ collection: C) {
    self.collection = collection
    index = self.collection.startIndex
  }

  mutating func next() -> C? {
    guard index < collection.endIndex else { return nil }
    let element1 = collection[index]
    index = collection.index(after: index)
    guard index < collection.endIndex else { return nil }
    let element2 = collection[index]
    let pair = [element1,element2]
    return C(pair)
  }
}

do {
  print("Pairs from array")
  let array = ["A","B","C"]
  let pairs = Pairs(array)
  for pair in pairs {
    print(pair)
  }
}

do {
  print("Pairs from set")
  let set = Set(["A","B","C"])
  let pairs = Pairs(set)
  for pair in pairs {
    print(pair)
  }
}