×

# 第三篇：AnyIterator ， AnySequence ，IteratorOverOne的补充解释

## AnyIterator

MyIterator 等价于 AnyIterator，实质是传入一个生成下一个元素的闭包

``````struct MyIterator<Element>:IteratorProtocol {
var base:()->Element?
init(_ body: @escaping () -> Element?) {
base = body
}

func next() -> Element? {
return base()
}
}

var x = 7
let iterator:MyIterator<Int> = MyIterator {
defer { x += 1 }
return x < 15 ? x : nil
}

iterator.next()
``````

``````extension MyIterator:Sequence {}

var x = 7
let iterator:MyIterator<Int> = MyIterator {
defer { x += 1 }
return x < 15 ? x : nil
}

iterator.next() // 输出7

for y in iterator {
print(y) // 输出 8 9 10 11 12 13 14
}
``````

/// Every `IteratorProtocol` can also be a `Sequence`. Note that
/// traversing the sequence consumes the iterator.
extension AnyIterator : Sequence {
}

``````/// To add `Sequence` conformance to your own custom type, add a
/// `makeIterator()` method that returns an iterator.

/// 重点看这里
/// Alternatively, if your type can act as its own iterator, implementing the
/// requirements of the `IteratorProtocol` protocol and declaring conformance
/// to both `Sequence` and `IteratorProtocol` are sufficient.
``````

``````protocol SequenceType {
associatedtype Iterator : IteratorProtocol
func makeIterator() -> Self.Iterator
}

extension SequenceType {
func makeIterator() -> Self.Iterator {
return self as! Self.Iterator
}
}
``````

## AnySequence

Sequence 其实是要关联一个数据源，姑且称之为 `content`；然后关联一个生成器`iterator`,将 `content` 中的元素一个个取出。

``````public struct AnySequence<Element> : Sequence {

public init<S : Sequence where S.Iterator.Element == Element, S.SubSequence : Sequence, S.SubSequence.Iterator.Element == Element, S.SubSequence.SubSequence == S.SubSequence>(_ base: S)

public init<I : IteratorProtocol where I.Element == Element>(_ makeUnderlyingIterator: @escaping () -> I)

...
}
``````

## IteratorOverOne

``````func one<A>(x: A) -> AnySequence<A> {
return AnySequence(IteratorOverOne(x))
}
``````

Swift 函数式编程 0 -> 1