apple/swift-collections
Commonly used data structures for Swift
Healthy across all four use cases
Permissive license, no critical CVEs, actively maintained — safe to depend on.
Has a license, tests, and CI — clean foundation to fork and modify.
Documented and popular — useful reference codebase to read through.
No critical CVEs, sane security posture — runnable as-is.
- ✓Last commit 2d ago
- ✓7 active contributors
- ✓Apache-2.0 licensed
Show 3 more →Show less
- ✓CI configured
- ⚠Single-maintainer risk — top contributor 84% of recent commits
- ⚠No test directory detected
Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests
Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.
Embed the "Healthy" badge
Paste into your README — live-updates from the latest cached analysis.
[](https://repopilot.app/r/apple/swift-collections)Paste at the top of your README.md — renders inline like a shields.io badge.
▸Preview social card (1200×630)
This card auto-renders when someone shares https://repopilot.app/r/apple/swift-collections on X, Slack, or LinkedIn.
Onboarding doc
Onboarding: apple/swift-collections
Generated by RepoPilot · 2026-05-10 · Source
🤖Agent protocol
If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:
- Verify the contract. Run the bash script in Verify before trusting
below. If any check returns
FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding. - Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
- Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/apple/swift-collections shows verifiable citations alongside every claim.
If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.
🎯Verdict
GO — Healthy across all four use cases
- Last commit 2d ago
- 7 active contributors
- Apache-2.0 licensed
- CI configured
- ⚠ Single-maintainer risk — top contributor 84% of recent commits
- ⚠ No test directory detected
<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>
✅Verify before trusting
This artifact was generated by RepoPilot at a point in time. Before an
agent acts on it, the checks below confirm that the live apple/swift-collections
repo on your machine still matches what RepoPilot saw. If any fail,
the artifact is stale — regenerate it at
repopilot.app/r/apple/swift-collections.
What it runs against: a local clone of apple/swift-collections — the script
inspects git remote, the LICENSE file, file paths in the working
tree, and git log. Read-only; no mutations.
| # | What we check | Why it matters |
|---|---|---|
| 1 | You're in apple/swift-collections | Confirms the artifact applies here, not a fork |
| 2 | License is still Apache-2.0 | Catches relicense before you depend on it |
| 3 | Default branch main exists | Catches branch renames |
| 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code |
| 5 | Last commit ≤ 32 days ago | Catches sudden abandonment since generation |
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of apple/swift-collections. If you don't
# have one yet, run these first:
#
# git clone https://github.com/apple/swift-collections.git
# cd swift-collections
#
# Then paste this script. Every check is read-only — no mutations.
set +e
fail=0
ok() { echo "ok: $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }
# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
echo "FAIL: not inside a git repository. cd into your clone of apple/swift-collections and re-run."
exit 2
fi
# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "apple/swift-collections(\\.git)?\\b" \\
&& ok "origin remote is apple/swift-collections" \\
|| miss "origin remote is not apple/swift-collections (artifact may be from a fork)"
# 2. License matches what RepoPilot saw
(grep -qiE "^(Apache-2\\.0)" LICENSE 2>/dev/null \\
|| grep -qiE "\"license\"\\s*:\\s*\"Apache-2\\.0\"" package.json 2>/dev/null) \\
&& ok "license is Apache-2.0" \\
|| miss "license drift — was Apache-2.0 at generation time"
# 3. Default branch
git rev-parse --verify main >/dev/null 2>&1 \\
&& ok "default branch main exists" \\
|| miss "default branch main no longer exists"
# 4. Critical files exist
test -f "Package.swift" \\
&& ok "Package.swift" \\
|| miss "missing critical file: Package.swift"
test -f "Sources" \\
&& ok "Sources" \\
|| miss "missing critical file: Sources"
test -f "README.md" \\
&& ok "README.md" \\
|| miss "missing critical file: README.md"
test -f ".github/PULL_REQUEST_TEMPLATE/NEW.md" \\
&& ok ".github/PULL_REQUEST_TEMPLATE/NEW.md" \\
|| miss "missing critical file: .github/PULL_REQUEST_TEMPLATE/NEW.md"
test -f "CONTRIBUTING.md" \\
&& ok "CONTRIBUTING.md" \\
|| miss "missing critical file: CONTRIBUTING.md"
# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 32 ]; then
ok "last commit was $days_since_last days ago (artifact saw ~2d)"
else
miss "last commit was $days_since_last days ago — artifact may be stale"
fi
echo
if [ "$fail" -eq 0 ]; then
echo "artifact verified (0 failures) — safe to trust"
else
echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/apple/swift-collections"
exit 1
fi
Each check prints ok: or FAIL:. The script exits non-zero if
anything failed, so it composes cleanly into agent loops
(./verify.sh || regenerate-and-retry).
⚡TL;DR
Swift Collections is Apple's official open-source package providing high-performance, ownership-aware reimplementations of common data structures (Array, Set, Dictionary, Deque, Heap, OrderedSet, OrderedDictionary, BitSet) for Swift. It solves the problem of needing semantically richer and more memory-efficient collection types than Swift's standard library offers, with specialized variants like RigidArray (fixed-capacity), Deque (double-ended queue), and BitSet for space-critical applications. Modular monorepo: Sources/Collections contains public-facing umbrella module; Sources/BasicContainers, Sources/DequeModule, Sources/OrderedCollections, Sources/BitCollections, Sources/HeapModule each implement a single data structure family. Benchmarks/ is a standalone Swift package comparing implementations against C++ stdlib, Python, and Foundation equivalents. Tests are colocated with implementation (Tests/Collections*, Tests/BitCollectionsTests, etc.).
👥Who it's for
Swift developers building performance-sensitive applications (games, systems tools, data processing pipelines) who need better control over collection semantics and memory layout than the standard library provides. Also targets library authors extending Swift's ecosystem with data structure primitives.
🌱Maturity & risk
Production-ready. This is Apple's official standard library extension package with comprehensive test coverage (test targets visible throughout Sources/), active CI/CD via .github/workflows/pull_request.yml, and stable APIs marked by the presence of both stable modules (BasicContainers, DequeModule, OrderedCollections, BitCollections, HeapModule) and experimental traits (UnstableContainersPreview, UnstableHashedContainers). Actively maintained with recent module additions.
Minimal risk. Single maintainer (Apple) provides long-term stability guarantees, but introduces version-coupling to Swift toolchain releases (requires specific Swift version minimums). Risk is primarily in the experimental modules (UnstableContainersPreview, UnstableSortedCollections) which may have breaking API changes—use only stable modules in production code. No high external dependency risk visible in the structure.
Active areas of work
Active development on multiple stable modules with recent focus on expanding ordered collections (OrderedDictionary, OrderedSet), bitwise operations (BitSet, BitArray), and heap implementations. Experimental modules tracking unstable features (sorted collections, hashed containers preview). Benchmarking infrastructure actively maintained with C++, Python, and Foundation comparison suites.
🚀Get running
git clone https://github.com/apple/swift-collections.git
cd swift-collections
swift build
swift test
Daily commands:
Development: swift build compiles all modules. swift test runs complete test suite. Benchmarks: cd Benchmarks && swift build && swift run <BenchmarkName> (see Benchmarks/Sources/Benchmarks/ for available benchmarks like ArrayBenchmarks, DequeBenchmarks, HeapBenchmarks).
🗺️Map of the codebase
Package.swift— Root package manifest defining all collection modules, targets, and dependencies; essential for understanding the project structure and build configuration.Sources— Main source directory containing all data structure implementations organized by module; primary entry point for understanding the codebase.README.md— Comprehensive overview of all stable and experimental data structures with module descriptions and usage guidance..github/PULL_REQUEST_TEMPLATE/NEW.md— Documents contribution standards and PR requirements that all contributors must follow.CONTRIBUTING.md— Official contribution guidelines covering development workflow, testing requirements, and code quality standards.Benchmarks/Package.swift— Benchmark suite configuration; critical for performance validation and understanding the testing infrastructure.
🧩Components & responsibilities
- Deque Module (Swift, ring buffer data structure) — Double-ended queue with O(1) append/prepend; ring buffer implementation for efficient front and back access.
- Failure mode: Out-of-bounds access on empty deque; unbalanced growth if only one end accessed repeatedly.
- OrderedSet / OrderedDictionary (Swift, hash tables, order tracking) — Preserves insertion order while providing fast lookups; combines array ordering with hash table lookups.
- Failure mode: Memory overhead from dual storage (array + hash table); performance degradation if many insertions/deletions.
- Heap Module (Swift, binary tree heap) — Min/max heap implementing priority queue; maintains heap invariant across insertions and deletions.
- Failure mode: Incorrect ordering if comparator violates transitivity; performance penalty for
🛠️How to make changes
Add a New Collection Data Structure
- Create a new module directory in Sources/ (e.g., Sources/NewCollection/) with your data structure implementation (
Sources/) - Add the new module target to Package.swift with appropriate dependencies and export statements (
Package.swift) - Create corresponding benchmark file in Benchmarks/Sources/Benchmarks/ to measure performance against stdlib and competing implementations (
Benchmarks/Sources/Benchmarks/NewCollectionBenchmarks.swift) - Add benchmark JSON result file to Benchmarks/Libraries/ directory for result tracking (
Benchmarks/Libraries/NewCollection.json) - Update README.md to document the new collection in the appropriate module section with usage examples (
README.md) - Create PR following the template in .github/PULL_REQUEST_TEMPLATE/NEW.md with performance data and documentation (
.github/PULL_REQUEST_TEMPLATE/NEW.md)
Add Benchmarks for Comparison Libraries
- Create benchmark wrapper file in Benchmarks/Sources/Benchmarks/ (e.g., NewLanguageBenchmarks.swift) that calls foreign code (
Benchmarks/Sources/Benchmarks/) - Add C++ benchmarks in Benchmarks/Sources/CppBenchmarks/src/ or Rust benchmarks in Benchmarks/Sources/RustBenchmarks/ (
Benchmarks/Sources/CppBenchmarks/src/) - Register the new benchmark in Benchmarks/Package.swift as a build target (
Benchmarks/Package.swift) - Execute benchmark tool and add results JSON to Benchmarks/Libraries/ directory (
Benchmarks/Libraries/)
Document a Collection Module
- Create a new markdown file in Documentation/ (e.g., Documentation/NewCollection.md) with API overview and examples (
Documentation/) - Add links and descriptions to the appropriate section in README.md under module table of contents (
README.md) - If announcing a new collection, create entry in Documentation/Announcement-benchmarks/ with benchmark results (
Documentation/Announcement-benchmarks/)
🔧Why these technologies
- Swift — Native implementation language enabling high-performance collection structures with full standard library integration and type safety.
- C++ Benchmarking — Provides performance baselines via std::vector, std::deque, std::map to validate Swift implementations against proven algorithms.
- Rust Benchmarking — Compares against Rust's Vec and HashMap to establish cross-language performance expectations for collection operations.
- Swift Package Manager — Modular package structure allows separate importable modules (DequeModule, OrderedCollections, BitCollections, etc.) with isolated dependencies.
⚖️Trade-offs already made
-
Separate benchmark suite with foreign language comparisons
- Why: Rigorous performance validation requires baseline comparisons; isolated Benchmarks/ package avoids bloating main library.
- Consequence: Build complexity increases; developers need C++/Rust toolchain to run full benchmarks locally.
-
Multiple data structure modules vs single monolithic package
- Why: Modular design (DequeModule, BitCollections, HashTreeCollections, etc.) allows fine-grained imports and reduces dependency bloat for users.
- Consequence: Package discovery and naming complexity; users must learn which module contains which collection.
-
Emphasis on algorithmic correctness and performance over feature completeness
- Why: Swift standard library often provides feature-rich but slower collections; Swift Collections targets performance-critical use cases.
- Consequence: API surface may be narrower; advanced features from stdlib (like custom comparators) may not be available in all collections.
🚫Non-goals (don't propose these)
- Does not aim to replace Swift standard library collections; complements with specialized high-performance alternatives.
- Not a real-time or lock-free library; no guarantees for concurrent access without external synchronization.
- Does not provide platform-specific optimizations (e.g., SIMD vectorization); pure Swift implementations for portability.
🪤Traps & gotchas
Swift version coupling: minimum Swift toolchain version requirement (check Package.swift) varies per module—experimental features require newer toolchain than stable ones. Benchmark comparisons require C++ compiler and Python installed (cmake and python in path). BitSet implementation uses bit-packing internals; mutations during iteration undefined behavior (like stdlib Set). OrderedCollections maintain dual index/key mappings; understanding the internal hash-backing is needed to avoid O(n) operations. Test discovery uses Swift Package Manager conventions—tests must be in Tests/TargetName/.
🏗️Architecture
💡Concepts to learn
- Value-Type Semantics with Copy-on-Modification — All collections in this library use Swift's value type model (structs) with copy-on-write backing; critical to understand mutation behavior and memory efficiency across all data structures
- Double-Ended Queue (Deque) Circular Buffer Implementation — Deque uses circular buffer technique internally to achieve O(1) insertion/removal at both ends; understanding this pattern is essential for Deque modifications and optimization
- Hash-Ordered Dual Indexing (OrderedCollections) — OrderedSet and OrderedDictionary maintain insertion order via dual indices while preserving O(1) lookup via hashing; unique pattern not present in stdlib that requires careful synchronization
- Bit-Packing and Bitwise Collections — BitSet and BitArray pack multiple boolean values into single machine words using bitwise operations; understanding bit layouts and endianness is critical for debugging and optimization
- Ownership-Aware Generic Constraints (Equatable, Hashable, Comparable) — This library extensively uses Swift's protocol-based generics with ownership awareness; mastering conditional conformances and where clauses is essential for extending or modifying collection types
- Heap Data Structure (Min/Max Heap Variants) — Heap module provides both min-heap and max-heap implementations via generic ordering; understanding heap invariants and heap-based priority queue semantics is essential for HeapModule usage
- Swift Package Manager Traits and Experimental Features — This library uses SPM's experimental 'traits' feature (UnstableContainersPreview, UnstableHashedContainers, UnstableSortedCollections) to gate unstable APIs; understanding trait mechanics is critical for dependency management and opting into experimental features
🔗Related repos
apple/swift-algorithms— Companion official Apple library providing algorithm implementations (sorting, searching, permutations) that operate on swift-collections data structuresapple/swift-standard-library— Swift standard library itself; swift-collections extends and improves upon stdlib collection types with specialized ownership semanticsrealm/realm-swift— Alternative collection storage for persistence use cases; uses similar value-type patterns but adds transactional guaranteespointfreeco/swift-collections— Community functional data structure library (immutable collections, persistent structures) using different design philosophy than Apple's mutable-ownership approachapple/swift-package-manager— Dependencies: swift-collections uses SPM exclusively for packaging and distribution; understanding SPM is essential for local development
🪄PR ideas
To work on one of these in Claude Code or Cursor, paste:
Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.
Add comprehensive benchmark comparison documentation for all data structures
The repo has extensive benchmarks (Benchmarks/Libraries/*.json) comparing Swift Collections against C++ std, Rust, and Foundation implementations, but there's no markdown documentation summarizing these results. New contributors could create a BENCHMARKS.md file that documents performance characteristics, trade-offs, and recommendations for each data structure (Deque, OrderedDictionary, OrderedSet, Heap, etc.), making it easier for users to choose the right structure.
- [ ] Create Benchmarks/BENCHMARKS.md documenting findings from Benchmarks/Libraries/*.json files
- [ ] Add performance comparison tables for each data structure (Array, Deque, Heap, OrderedDictionary, OrderedSet, TreeDictionary, TreeSet, BitSet, BigString)
- [ ] Include specific use-case recommendations and trade-off analysis
- [ ] Link to benchmark results from main README.md
Implement unified benchmark result analysis script
The Benchmarks directory contains multiple *.json files but no automated way to parse, compare, and generate reports from them. Adding a Swift script (or Python tool) in Benchmarks/Scripts/ to compare benchmark results across runs, track performance regressions, and generate HTML/markdown reports would be valuable for CI/CD integration and PR performance validation.
- [ ] Create Benchmarks/Scripts/ directory with benchmark analysis tool
- [ ] Implement JSON parsing for Benchmarks/Libraries/*.json files
- [ ] Add regression detection logic (flag performance degradation > 5%)
- [ ] Generate human-readable comparison reports (HTML or Markdown)
- [ ] Integrate with .github/workflows/pull_request.yml to run on PRs
Add specific unit test coverage for edge cases in OrderedCollections and HashTreeCollections modules
The file structure shows benchmark tests for OrderedDictionary, OrderedSet, TreeDictionary, and TreeSet, but based on the partial README, these modules likely need more comprehensive unit test coverage for edge cases (empty collections, single-element operations, memory stress). Creating a dedicated test file for each module's boundary conditions would catch subtle bugs early.
- [ ] Review Tests directory structure for OrderedCollections and HashTreeCollections test files
- [ ] Add unit tests for edge cases: empty collections, single elements, large insertions/deletions
- [ ] Add tests for iterator invalidation patterns and thread-safety assumptions
- [ ] Add tests comparing behavior against equivalent Swift standard library operations
- [ ] Document test coverage gaps in a TESTING.md file referencing which scenarios are covered
🌿Good first issues
- Add comprehensive documentation examples to HeapModule public API (Benchmarks/Libraries/Heap.json shows API gaps); create doc comment blocks with usage examples in Sources/HeapModule following OrderedCollections documentation style
- Extend BitSet benchmark comparisons to cover BitArray (mentioned in .spi.yml but Benchmarks/Libraries/ lacks BitArray.json); add BitArrayBenchmarks.swift comparing against Foundation's CFBitVector and C++ bitset
- Add missing test coverage for edge cases in RigidArray (fixed-capacity array); create Tests/BasicContainersTests/RigidArrayEdgeCasesTests.swift covering capacity-exhaustion errors and copy-on-modify semantics
⭐Top contributors
Click to expand
Top contributors
- @lorentey — 84 commits
- @kastiglione — 7 commits
- @FranzBusch — 3 commits
- @dependabot[bot] — 3 commits
- @manojmahapatra — 1 commits
📝Recent commits
Click to expand
Recent commits
03cc312— Merge pull request #647 from lorentey/work/release-prep (lorentey)599e65a— Silence bogus license checker error for the FormatterFixtures package manifest (lorentey)8ecf8c7— [Xcode] Don’t enable traits by default (lorentey)3614f74— Clean up package manifest (lorentey)c38e47d— [BasicContainers, DequeModule] Avoid using deprecated API (lorentey)72ee2bf— [BasicContainers] Update CMakeLists.txt (lorentey)f196269— Define placeholder availability macro for SwiftStdlib 6.5 (lorentey)f83bd74— Move FormatterFixtures into a nested package (lorentey)e5236d4— Update README (lorentey)db24e1b— Merge pull request #646 from lorentey/work/mutableref (lorentey)
🔒Security observations
The apple/swift-collections repository demonstrates good security posture overall. As a pure Swift data structures library, it avoids common injection vulnerabilities (SQLi, XSS) inherent to web applications. No hardcoded secrets or credentials were identified in the provided file structure. The main security considerations are: (1) ensuring Dependabot is properly configured to detect vulnerable dependencies, (2) reviewing C++ benchmark code for memory safety issues, and (3) auditing Rust code for unsafe patterns. The codebase appears well-maintained by Apple with appropriate CI/CD configuration. No critical or high-severity vulnerabilities were detected from the visible file structure.
- Low · Dependabot Configuration Present —
.github/dependabot.yml. The repository contains a .github/dependabot.yml configuration file. While Dependabot itself is a security tool, the configuration should be reviewed to ensure it's checking all dependencies for known vulnerabilities and enforcing security updates appropriately. Fix: Verify that Dependabot is configured to check for security vulnerabilities and that automated security updates are enabled with appropriate review requirements. - Low · C++ Benchmark Code Included —
Benchmarks/Sources/CppBenchmarks/. The repository includes C++ benchmark code (Benchmarks/Sources/CppBenchmarks/). C++ code can be more prone to memory safety issues (buffer overflows, use-after-free) compared to Swift. If this code is compiled and executed, it could introduce security risks. Fix: Ensure C++ code follows secure coding practices, use static analysis tools (clang-analyzer, cppcheck), enable compiler security flags (-fstack-protector-all, -D_FORTIFY_SOURCE=2), and perform code reviews focusing on memory safety. - Low · Rust Benchmark Code Included —
Benchmarks/Sources/RustBenchmarks/. Rust code is included in the benchmarks (Benchmarks/Sources/RustBenchmarks/). While Rust has memory safety guarantees, unsafe blocks can still introduce vulnerabilities. The presence of external Rust code should be reviewed. Fix: Review any unsafe {} blocks in Rust code, ensure dependencies are up-to-date, and use cargo-audit to check for known vulnerabilities in Rust dependencies.
LLM-derived; treat as a starting point, not a security audit.
👉Where to read next
- Open issues — current backlog
- Recent PRs — what's actively shipping
- Source on GitHub
Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.