Collections in Depth

43.1 The Collection Protocol Hierarchy

Sequence (makeIterator, single pass possible)
└── Collection (indices, multi-pass, subscript)
    ├── BidirectionalCollection (index(before:), last, reversed)
    │   └── RandomAccessCollection (O(1) index distance: Array, ContiguousArray)
    ├── MutableCollection (subscript set: sort in place)
    └── RangeReplaceableCollection (append, insert, remove)

43.2 Lazy Sequences

let firstThreeEvenSquares = (1...)
    .lazy
    .map { $0 * $0 }
    .filter { $0.isMultiple(of: 2) }
    .prefix(3)
Array(firstThreeEvenSquares)          // [4, 16, 36]: computed on demand

43.3 Custom Collection

struct Ring<Element>: RandomAccessCollection {
    private var storage: [Element]
    private let offset: Int
    init(_ elements: [Element], rotatedBy offset: Int) { storage = elements; self.offset = offset }
    var startIndex: Int { 0 }
    var endIndex: Int { storage.count }
    subscript(position: Int) -> Element { storage[(position + offset) % storage.count] }
}
let ring = Ring([1, 2, 3, 4], rotatedBy: 1)
Array(ring)                            // [2, 3, 4, 1]: and you get map, filter, reversed, etc. for free

43.4 Specialized Collections and Algorithms

Standard library: ContiguousArray, ArraySlice, Range, StrideTo, repeatElement, zip, sequence(first:next:), stride, KeyValuePairs, CollectionOfOne, EmptyCollection.

swift-collections: Deque, OrderedSet, OrderedDictionary, Heap, BitSet, BitArray, TreeSet/TreeDictionary (persistent).

swift-algorithms: chunks(ofCount:), windows(ofCount:), combinations, permutations, uniqued(), partitioned(by:), min(count:), adjacentPairs(), cycled(), randomSample(count:), striding(by:), indexed().

swift-numerics (Complex, Real protocols), swift-system (low-level file APIs), swift-argument-parser (CLIs).