Swift 里集合类型协议的关系

Sequence

A type that provides sequential, iterated access to its elements.

是最基础的协议,可以通过迭代来获取它的元素。
有两个关联类型:

  /// A type representing the sequence's elements.
  associatedtype Element

  /// A type that provides the sequence's iteration interface and
  /// encapsulates its iteration state.
  associatedtype Iterator : IteratorProtocol where Iterator.Element == Element

遵守Sequence 协议,只需要实现makeIterator()方法即可。 在迭代过程中,Sequence的序列是否被破坏,并没有要求。因此,两次迭代同一个Sequence,可能会得到不同的结果。

Collection

A sequence whose elements can be traversed multiple times, nondestructively, and accessed by an indexed subscript.

sequence基础上,增加了几个性质

  1. 多次遍历,不会对序列的结构造成影响
  2. 可以通过下标索引

引入了几个和索引相关的关联类型

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

通过下标获取值的方法如下,复杂度是O(1)

subscript(position: Index) -> Element { get }

可以通过下标来遍历,那么必须定义下标的successor

func index(after i: Self.Index) -> Self.Index

BidirectionalCollection

A collection that supports backward as well as forward traversal.

继承了Collection协议,增加了可以反向遍历的功能。
通过一个下标,可以找到上一个下标。

func index(before i: Index) -> Index

这也为和last相关的方法提供了基础

RandomAccessCollection

A collection that supports efficient random-access index traversal.

继承了BidirectionalCollection,因此可以正向/反向遍历。还对遍历的效率做出来要求,

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协议,提供了可以改变元素值的能力。

override subscript(position: Index) -> Element { get set }

这个下标操作,提供了set方法。 对应的,提供了默认的分片方法(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,增加了可以某一个子区间内的元素,可以被另一个collection替代的能力。
collection增加了插入和删除的能力。

  mutating func append(_ newElement: __owned Element)
  mutating func append<S : Sequence>(contentsOf newElements: __owned S)
    where S.Element == Element
  mutating func insert(_ newElement: __owned Element, at i: Index)
  mutating func insert<S : Collection>(contentsOf newElements: __owned S, at i: Index)
    where S.Element == Element
  mutating func remove(at i: Index) -> Element
  mutating func removeSubrange(_ bounds: Range<Index>)

猜你喜欢

转载自www.cnblogs.com/huahuahu/p/Swift-li-ji-he-lei-xing-xie-yi-de-guan-xi.html
今日推荐