数组和集合 / 迭代器

struct Counter: Sequence, IteratorProtocol {
    private var current: Int
    private let high: Int
    private let step: Int

    init(low: Int, high: Int, step: Int) {
        self.current = low
        self.high = high
        self.step = step
    }

    //nil ends the iteration
    mutating func next() -> Int? {
        if current > high {
            return nil
        }
        defer { current += step }
        return current
    }
}

var iterator = Counter(
    low: 3, high: 9, step: 2)
while let n = iterator.next() {
    print(n)
}
//printed 3, 5, 7, 9

//Sequence gives "for-in" for free
for n in Counter(low: 3, high: 9, step: 2) {
    print(n)
}