Iterator
迭代器 Iterator 是從 Sequence 繼承的類型,在遍歷序列時管理遍歷狀態,Sequence 也通過迭代器訪問元素。這次我們實現一個數組雙向迭代器。
let numbers = [0, 1, 2, 3]
var _numIterator: BidirectionalIterator<[Int]>?
雙向迭代器.gif
Demo:
https://github.com/wiiale/AdvancedSwiftThinker/tree/master/T02-Iterator-Bidirectional
實現雙向迭代器
import Foundation
struct BidirectionalIterator<Elements> where Elements: BidirectionalCollection {
let _elements: Elements
var _position: Elements.Index
init(elements: Elements) {
self._elements = elements
self._position = elements.startIndex
}
mutating func next() -> Elements.Element? {
if _position == _elements.endIndex { return nil }
let element = _elements[_position]
_elements.formIndex(after: &_position)
return element
}
mutating func previous() -> Elements.Element? {
if _position == _elements.startIndex { return nil }
_elements.formIndex(before: &_position)
let element = _elements[_position]
return element
}
}
extension BidirectionalCollection {
func makeBidirectionalIterator() -> BidirectionalIterator<Self> {
return BidirectionalIterator(elements: self)
}
}
與必須實現的next()
方法一樣,制造previous()
方法實現雙向。其中 _position 記錄 Index,要注意在不返回 nil 的情況下,next 操作時先取后增 _position,previous 操作時先減 _position 后取值。
使用
let numbers = [0, 1, 2, 3]
var it = numbers.makeBidirectionalIterator()
it.next() // 0
it.next() // 1
it.next() // 2
it.next() // 3
it.next() // nil
it.next() // nil
it.previous() // 3
it.previous() // 2
it.previous() // 1
it.previous() // 0
it.previous() // nil
it.previous() // nil
it.next() // 0
本冊文集中以“提出簡單需求->簡單實現需求片段”為流程,內容只針對該知識點實現的業務實例進行熟悉,業務也必定存在比文章方法更好的實現方式,文章旨在分析知識點并加深理解。文集不普及基本知識,不包含《Swift 進階》書籍的詳細內容。深入學習Swift請大家支持正版書籍(ObjC 中國)