Swift Collections Documentation

repository·main·Indexed 26 days ago

https://github.com/apple/swift-collections

An open-source package providing high-performance, specialized data structure implementations for Swift. It includes stable modules for Deques, OrderedSet, OrderedDictionary, BitSet, BitArray, Heap, and persistent hashed collections (TreeSet, TreeDictionary). The library also offers ownership-aware containers for systems programming and experimental features gated behind package traits such as UnstableContainersPreview, UnstableHashedContainers, and UnstableSortedCollections.

Tokens
25.7K
Snippets
43
Records
166
Agent score
83%

What's inside Swift Collections

  1. Overview of Swift Collections modules

    main

    Swift Collections is an open-source package providing specialized data structure implementations. The package is organized into several modules based on use cases:

    • Basic Containers: Provides UniqueArray and RigidArray, which are noncopyable array variants designed for more predictable performance compared to the standard Array.
    • Bit Collections: Provides BitSet and BitArray for dynamic bit-level collections.
    • Deque Module: Provides Deque<Element>, a double-ended queue implemented via a ring buffer. It supports range-replacement, mutation, and random access.
    • Heap Module: Provides Heap, a min-max heap backed by an array, ideal for priority queue implementations.
    • Ordered Collections: Provides OrderedSet<Element> (an ordered variant of Set) and OrderedDictionary<Key, Value> (an ordered variant of Dictionary). These maintain a well-defined order of elements.
    • Hash Tree Collections: Provides TreeSet and TreeDictionary, which are persistent hashed collections using Compressed Hash-Array Mapped Prefix Trees (CHAMP). These are optimized for scenarios involving mutations of shared copies.
    • Trailing Elements Module: Provides TrailingArray, a low-level ManagedBuffer variant designed for interoperability with C constructs using fixed-size headers followed by variable-size storage.
  2. Overview of Swift Collections stable data structures

    main

    Swift Collections provides several specialized data structure implementations organized into thematic modules. These include:

    • BasicContainers: Ownership-aware reimplementations of standard types like UniqueArray<Element> and RigidArray<Element>.
    • DequeModule: Double-ended queue implementations including Deque<Element> (copy-on-write), UniqueDeque<Element> (noncopyable), and RigidDeque<Element> (fixed-capacity).
    • OrderedCollections: Variants of Set and Dictionary that preserve insertion order, specifically OrderedSet<Element> and OrderedDictionary<Key, Value>.
    • BitCollections: Efficient bit maps including BitSet (for Set<Int>) and BitArray (for Array<Bool>).
    • HeapModule: A min-max heap (Heap<Element>) suitable for priority queues.
    • HashTreeCollections: Persistent hashed collections using CHAMP, including TreeSet<Element> and TreeDictionary<Key, Value> for efficient mutations of shared copies.
    • TrailingElementsModule: Low-level tools for C interoperability, including TrailingArray, TrailingPadding<Header>, and the TrailingElements protocol.
    • ContainersPreview: Experimental ownership-aware containers (requires UnstableContainersPreview trait), featuring UniqueBox<Value>.
  3. Overview of Ownership-Aware Containers in Swift Collections

    main
    Swift Collections includes several ownership-aware data structures designed for high-performance systems programming. These types are built to support noncopyable and nonescapable elements, providing precise control over memory and runtime behavior. Unlike standard Swift Collections, these containers are optimized for environments with strict performance constraints and can handle types that cannot be copied or escaped.
  4. Understand the Container protocol design

    main

    The Container protocol is an ownership-aware analogue of Collection. It represents a type that physically holds its contents in memory, making them directly accessible. Unlike Iterable types that might generate items on demand (generative iteration), Container types are restricted to visitative semantics, meaning elements must pre-exist in the container.

    Key characteristics:

    • Predictable Performance: count must be returned in $O(1)$ complexity.
    • Non-destructive: Contents can be traversed multiple times without changing the container.
    • Error-free iteration: Failure is required to be Never because elements are pre-existing and always accessible.
    • Refines Iterable: All Iterable algorithms work with Container types.
  5. Understand the Swift Collections ownership-aware iteration model

    main

    The Swift Collections library uses an ownership-aware container model designed to support noncopyable elements and improve performance through bulk iteration. The design space is defined by four axes:

    1. Elementwise vs. Bulk Iteration:

      • Elementwise (e.g., Sequence): Exposes one element at a time via next(). Simple but can be slow due to frequent protocol entry points.
      • Bulk (e.g., Iterable, Container): Exposes multiple elements at once using a Span. This is more efficient for piecewise contiguous storage.
    2. Borrowing vs. Taking Elements:

      • Borrowing (e.g., Iterable): Clients receive temporary, read-only access to elements. The container retains ownership.
      • Taking (e.g., Producer): Clients receive full ownership of the elements, which is necessary for noncopyable types if you want to move them out of a container.
    3. Generative vs. Visitative Iteration:

      • Generative (e.g., Iterable): Elements are materialized on the fly (e.g., a String's Characters). Elements may "evaporate" once the iterator advances.
      • Visitative (e.g., Container): Elements already exist in memory. Clients can safely hold references to them as long as the container isn't mutated.
    4. Failable vs. Non-failable Iteration:

      • Failable (e.g., Iterable): Iteration can throw errors (using typed throws). This is common for generative processes.
      • Non-failable (e.g., Container): Iteration cannot throw, as visiting existing memory is assumed to be safe.
  6. Use OrderedSet for unique, ordered collections

    main

    An OrderedSet is a collection of unique elements that maintains a specific user-specified order and supports efficient random-access traversal. It is a suitable alternative to Set when order matters, or to Array when you need uniqueness and fast membership testing.

    To use OrderedSet, import OrderedCollections and ensure your element type conforms to Hashable.

    import OrderedCollections
    
    let buildingMaterials: OrderedSet = ["straw", "sticks", "bricks"]
  7. Use ShareableSet and ShareableDictionary for efficient shared mutations

    main

    The ShareableHashedCollections module provides ShareableSet and ShareableDictionary. These are tree-based, unordered collections that use a prefix tree structure based on hash values.

    Unlike standard Set and Dictionary which use all-or-nothing copy-on-write (requiring a full copy of the storage upon the first mutation of a shared instance), ShareableSet and ShareableDictionary allow mutated copies to share as much of their structure as possible. This results in:

    • Logarithmic time complexity for mutations of shared copies (instead of linear).
    • Reduced memory usage because mutated copies share most of their underlying nodes.
    • Efficient set/dictionary operations (like subtracting) because shared subtrees can be skipped during comparison.

    Use these types when your application frequently takes snapshots of collections and performs mutations or diffing operations on those snapshots.

  8. Understand the Public API and Stability Guarantees

    main

    The swift-collections package is source-stable and follows Semantic Versioning.

    Stable Public API

    The stable public API consists of non-underscored declarations marked public within the following modules:

    • Collections
    • BasicContainers
    • BitCollections
    • ContainersPreview
    • DequeModule
    • HashTreeCollections
    • HeapModule
    • OrderedCollections
    • TrailingElementsModule

    Unstable APIs

    Do not rely on the following, as they may change or be removed in any release:

    • Underscored declarations: Any name containing a leading underscore (e.g., _someMember, _Bar, _FooModule).
    • Experimental Traits: Interfaces enabled via the UnstableContainersPreview, UnstableHashedContainers, or UnstableSortedCollections package traits.
    • Experimental Modules: SortedCollections and _RopeModule are currently unstable.
    • Non-SwiftPM builds: Configurations for CMake and Xcode are for internal use and are unstable.