Swift 中集合協(xié)議是數(shù)組、字典、集合和字符串實現(xiàn)的基礎(chǔ),有一些數(shù)據(jù)結(jié)構(gòu)和算法的知識,理解這部分內(nèi)容更容易一些。

Sequence 和 Iterator
Sequence 就是一串相同類型的值,可以在其上遍歷迭代:
protocol Sequence {
associatedtype Element // 序列中的元素
associatedtype Iterator: IteratorProtocol // 迭代器協(xié)議
func makeIterator() -> Iterator // 生成迭代器
}
迭代器協(xié)議聲明就比較簡單,next() 方法獲取下一個值,不能后退,也不能隨機訪問,next() 返回 nil 時表明迭代結(jié)束,所以也可以一直返回非 nil 的值就永遠(yuǎn)不結(jié)束:
protocol IteratorProtocol {
associatedtype Element
mutating func next() -> Element?
}
編譯器將 for loop 轉(zhuǎn)換為下面的迭代器代碼:
var iterator = someSequence.makeIterator()
while let element = iterator.next() {
doSomething(with: element)
}
如下的迭代器,輸入 “abc”,每次迭代生成 “a”、”ab” 和 “abc”:
struct PrefixIterator: IteratorProtocol {
let string: String
var offset: String.Index
init(string: String) {
self.string = string
offset = string.startIndex
}
mutating func next() -> Substring? {
guard offset < string.endIndex else { return nil }
string.formIndex(after: &offset)
return string[..<offset]
}
}
如下的 Sequence 使用了上面的迭代器,這個 Sequence 保存了輸入的字符串,makeIterator() 都是根據(jù)保存的字符串創(chuàng)建迭代器,然后在這個基礎(chǔ)進(jìn)行一次遍歷迭代,可以看出 Sequence 和迭代器的關(guān)系,迭代器就只是負(fù)責(zé)給出下一個值,有可能會改變一些初始值,Sequence 保存了初始值,以便創(chuàng)建迭代器時使用:
struct PrefixSequence: Sequence {
let string: String
func makeIterator() -> PrefixIterator {
return PrefixIterator(string: string)
}
}
Sequence 通常是只能單次遍歷,也有可以多次遍歷的情況,其語義并不保證可以多次遍歷,盡量實現(xiàn)成只能單次遍歷。
Collection
Collection 是可以無破壞多次遍歷、有限的序列,還可以通過下標(biāo)訪問。
Collection 協(xié)議是基于 Sequence 協(xié)議,滿足 Collection 協(xié)議需要實現(xiàn)內(nèi)容很多,但是因為有默認(rèn)實現(xiàn),最基本的需要實現(xiàn)的內(nèi)容如下,滿足了 Collection 協(xié)議后,就可以擁有很多功能,查看 Collection - Apple Developer Documentation:
protocol Collection: Sequence {
associatedtype Element // 序列中的元素
associatedtype Index: Comparable // 下標(biāo)
var startIndex: Index { get } // 第一個元素的下標(biāo)
var endIndex: Index { get } // 最后一個元素的下標(biāo) + 1
func index(after i: Index) -> Index // 當(dāng)前下標(biāo) + 1
subscript(position: Index) -> Element { get } // 下標(biāo)獲取元素
}
Array Literals 是數(shù)組語義,Swift 數(shù)組 和 Swift 集合 中有關(guān)于通過如下數(shù)組語義創(chuàng)建的代碼:
let evenNumbers = [2, 4, 6, 8]
var shoppingList = ["Eggs", "Milk"]
var genres: Set<String> = ["Rock", "Pop", "Jazz"]
通過實現(xiàn) ExpressibleByArrayLiteral 協(xié)議,你也可以擁有:
extension FIFOQueue: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Element...) {
self.init(left: elements.reversed(), right: [])
}
}
值得注意的 Associated Types:
- Iterator - 前面 Sequence 中已經(jīng)講過。
- Indices - Index 不一定只是通過 Int 實現(xiàn),滿足 Comparable 協(xié)議都可以,注意不能有指向 Collection 的引用,否則會有性能問題。查看 Advance Swift - Indices 了解更多。
- SubSequence - 也是 Collection,和原 Collection 共享所有元素,只是通過兩個下標(biāo)來限定范圍,可以通過 String(substring) 或 Array(arraySlice) 來拷貝元素創(chuàng)建新的 Collection。查看 Advance Swift - Subsequences 了解更多。
集合協(xié)議層級

BidirectionalCollection
BidirectionalCollection 支持向后遍歷和向前遍歷。
protocol BidirectionalCollection: Collection {
func index(before i: Index) -> Index // 當(dāng)前下標(biāo) - 1
}
RandomAccessCollection
RandomAccessCollection 支持常量時間的下標(biāo)計算。
protocol RandomAccessCollection: BidirectionalCollection {
func index(_ i: Index, offsetBy distance: Int) -> Index // 根據(jù)距離計算下標(biāo)
func distance(from start: Index, to end: Index) -> Int // 計算兩下標(biāo)的距離
}
MutableCollection
MutableCollection 支持原址元素修改。
protocol MutableCollection: Collection {
subscript(position: Index) -> Element { set } // 下標(biāo)修改元素
}
RangeReplaceableCollection
RangeReplaceableCollection 支持元素新增和元素刪除。
protocol RangeReplaceableCollection: Collection {
init() // 創(chuàng)建空集合
mutating func replaceSubrange<C>(_ subrange: Range<Index>, with newElements: C) // 替換下標(biāo)范圍的元素
where C : Collection, Element == C.Element
}
LazySequenceProtocol 和 LazyCollectionProtocol
LazySequenceProtocol 和 LazyCollectionProtocol 支持當(dāng)需要時才計算。
let filtered = standardIn.lazy.filter {
$0.split(separator: " ").count > 3
}
for line in filtered {
print(line)
}
(1..<100).lazy.map { $0 * $0 }.filter { $0 > 10 }.map { "\($0)"}