Swift 里集合类型协议的关系


Sequence
A type that provides sequential, iterated access to its elements.
是最基礎(chǔ)的協(xié)議,可以通過(guò)迭代來(lái)獲取它的元素。
有兩個(gè)關(guān)聯(lián)類型:
遵守Sequence 協(xié)議,只需要實(shí)現(xiàn)makeIterator()方法即可。 在迭代過(guò)程中,Sequence的序列是否被破壞,并沒(méi)有要求。因此,兩次迭代同一個(gè)Sequence,可能會(huì)得到不同的結(jié)果。
Collection
A sequence whose elements can be traversed multiple times, nondestructively, and accessed by an indexed subscript.
在sequence基礎(chǔ)上,增加了幾個(gè)性質(zhì)
引入了幾個(gè)和索引相關(guān)的關(guān)聯(lián)類型
associatedtype Index : Comparable /// A type that represents the indices that are valid for subscripting the /// collection, in ascending order. associatedtype Indices : Collection = DefaultIndices<Self> where Indices.Element == Index, Indices.Index == Index,Indices.SubSequence == Indices通過(guò)下標(biāo)獲取值的方法如下,復(fù)雜度是O(1)
subscript(position: Index) -> Element { get }可以通過(guò)下標(biāo)來(lái)遍歷,那么必須定義下標(biāo)的successor
func index(after i: Self.Index) -> Self.IndexBidirectionalCollection
A collection that supports backward as well as forward traversal.
繼承了Collection協(xié)議,增加了可以反向遍歷的功能。
通過(guò)一個(gè)下標(biāo),可以找到上一個(gè)下標(biāo)。
這也為和last相關(guān)的方法提供了基礎(chǔ)
RandomAccessCollection
A collection that supports efficient random-access index traversal.
繼承了BidirectionalCollection,因此可以正向/反向遍歷。還對(duì)遍歷的效率做出來(lái)要求,
Random-access collections can move indices any distance and measure the distance between indices in O(1) time
MutableCollection
A collection that supports subscript assignment.
繼承了collection協(xié)議,提供了可以改變?cè)刂档哪芰Α?/p> override subscript(position: Index) -> Element { get set }
這個(gè)下標(biāo)操作,提供了set方法。 對(duì)應(yīng)的,提供了默認(rèn)的分片方法(O(n))
/// - Complexity: O(*n*), where *n* is the length of the collection.mutating func partition(by belongsInSecondPartition: (Element) throws -> Bool) rethrows -> Index也提供了交換方法
/// - Complexity: O(1)mutating func swapAt(_ i: Index, _ j: Index)RangeReplaceableCollection
A collection that supports replacement of an arbitrary subrange of elements with the elements of another collection.
繼承了collection,增加了可以某一個(gè)子區(qū)間內(nèi)的元素,可以被另一個(gè)collection替代的能力。
為collection增加了插入和刪除的能力。
轉(zhuǎn)載于:https://www.cnblogs.com/huahuahu/p/Swift-li-ji-he-lei-xing-xie-yi-de-guan-xi.html
總結(jié)
以上是生活随笔為你收集整理的Swift 里集合类型协议的关系的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 显示器尺寸对照表_求解显示器屏幕尺寸对照
- 下一篇: [SCOI2009]最长距离