Conformar un nuevo protocolo de secuencia con una implementación predeterminada de makeIterator ()
Hice un (muy básico)BinaryTree
protocolo:
public enum BinaryTreeChildSide {
case left, right
}
public protocol BinaryTree {
associatedtype Element
associatedtype Index
func child(of index: Index, side: BinaryTreeChildSide) -> Index?
var rootIndex: Index? { get }
subscript(position: Index) -> Element { get }
}
Para un básicorecorrido iterativo en orden, Hice unaBinaryTreeIterator
(tenga en cuenta que no implementoSequence
todavía):
public extension BinaryTree {
func makeIterator() -> BinaryTreeIterator<Self> {
return BinaryTreeIterator(self)
}
}
public struct BinaryTreeIterator<Tree: BinaryTree>: IteratorProtocol {
private let tree: Tree
private var stack: [Tree.Index]
private var index: Tree.Index?
private init(_ tree: Tree) {
self.tree = tree
stack = []
index = tree.rootIndex
}
public mutating func next() -> Tree.Element? {
while let theIndex = index {
stack.append(theIndex)
index = tree.child(of: theIndex, side: .left)
}
guard let currentIndex = stack.popLast() else { return nil }
defer { index = tree.child(of: currentIndex, side: .right) }
return tree[currentIndex]
}
}
Implementar un montón binario en este protocolo también es bastante sencillo:
public struct BinaryHeap<Element> {
private var elements: [Element]
public init(_ elements: [Element]) {
self.elements = elements
}
}
extension BinaryHeap: BinaryTree {
private func safeIndexOrNil(_ index: Int) -> Int? {
return elements.indices.contains(index) ? index : nil
}
public func child(of index: Int, side: BinaryTreeChildSide) -> Int? {
switch side {
case .left: return safeIndexOrNil(index * 2 + 1)
case .right: return safeIndexOrNil(index * 2 + 2)
}
}
public var rootIndex: Int? { return safeIndexOrNil(0) }
public subscript(position: Int) -> Element {
return elements[position]
}
}
Hasta aquí todo bien. Ahora puedo hacer un montón simple e iterar a través de sus elementos:
let heap = BinaryHeap([4, 2, 6, 1, 3, 5, 7])
var iterator = heap.makeIterator()
while let next = iterator.next() {
print(next, terminator: " ")
}
// 1 2 3 4 5 6 7
Esto funciona, pero por supuesto el objetivo de implementarmakeIterator()
es conformarse aSequence
. sin embargo, si reemplazo
public protocol BinaryTree {
con
public protocol BinaryTree: Sequence {
entonces el compilador se queja de queBinaryHeap
no implementaSequence
porque el tipo asociadoIterator
No se puede inferir. Si especifico manualmente elIterator
escribir con
extension BinaryHeap: BinaryTree {
typealias Iterator = BinaryTreeIterator<BinaryHeap>
...
}
entonces el compilador muestra un error queIterator
circularmente se hace referencia a sí mismo. Entonces esa podría ser la razón por la queIterator
No se pudo inferir el tipo.
Curiosamente, funciona si envuelvo mi costumbreBinaryTreeIterator
en unAnyIterator
ejemplo:
public extension BinaryTree {
func makeIterator() -> AnyIterator<Element> {
return AnyIterator(BinaryTreeIterator(self))
}
}
let heap = BinaryHeap([4, 2, 6, 1, 3, 5, 7])
for number in heap {
print(number, terminator: " ")
}
// 1 2 3 4 5 6 7
De AppleIndexingIterator
parece funcionar de manera similar a miBinaryTreeIterator
:
public struct IndexingIterator<
Elements : IndexableBase
// FIXME(compiler limitation):
// Elements : Collection
> : IteratorProtocol, Sequence {
...
}
Desde elcódigo fuente. Quizás el problema que estoy enfrentando también podría deberse a la limitación del compilador mencionada allí, pero no estoy seguro.
¿Hay alguna forma de conformarse?BinaryTree
aSequence
sin usoAnyIterator
?