apple/swift
Standard library
Active contributors: airspeedswift, glessard, lorentey, KateOuO
Purpose
stdlib/public/core/ is the implementation of the Swift module -- the always-imported standard library. It provides the language's core types (Bool, Int, Double, String, Array, Dictionary, Set, Optional, ...), the protocol hierarchy that organizes them (Sequence, Collection, Hashable, Equatable, ...), and the syntactic surface for control flow (Range, Result, Error).
It is implemented in Swift on top of Builtin primitives and the C++ runtime (see Runtime). The directory contains 240+ source files.
Directory layout
stdlib/public/core/ (240 files)
├── Array.swift # Array (the canonical sequence currency type)
├── ArrayBuffer.swift, ContiguousArrayBuffer.swift, ArraySlice.swift, ContiguousArray.swift
├── Dictionary.swift, DictionaryStorage.swift, DictionaryBuilder.swift
├── Set.swift, SetStorage.swift
├── String.swift, StringObject.swift, StringStorage.swift, ...
├── StringNormalization.swift, StringComparable.swift, ...
├── Optional.swift
├── Sequence.swift, Collection.swift, MutableCollection.swift, BidirectionalCollection.swift, RandomAccessCollection.swift
├── Hashable.swift, Hasher.swift
├── Equatable.swift, Comparable.swift
├── Codable.swift # Encoding / Decoding protocols and conformances
├── ClosedRange.swift, Range.swift, Stride.swift
├── Integers.swift.gyb # generated numeric overloads
├── FloatingPoint.swift, FloatingPointTypes.swift.gyb
├── Bool.swift
├── Builtin.swift # the @_transparent wrappers around `Builtin.*`
├── Codable.swift, JSON-style encoders only via Foundation overlay (separate repo)
├── KeyPath.swift, AnyHashable.swift
├── Result.swift, Error.swift
├── ManagedBuffer.swift, ManagedStorage.swift
├── Pointer.swift, Unmanaged.swift, OpaquePointer.swift
├── Atomics, Mutex etc. moved to `stdlib/public/Synchronization/`
└── ... many moreKey abstractions
| Type | File | Description |
|---|---|---|
Array<Element> |
stdlib/public/core/Array.swift |
The currency-type sequence. Backed by _ContiguousArrayStorage. |
Dictionary<Key, Value> |
stdlib/public/core/Dictionary.swift |
Hash table with chaining, robin-hood hashing internally. |
Set<Element> |
stdlib/public/core/Set.swift |
Same hash-table backing as Dictionary. |
String |
stdlib/public/core/String.swift |
Tagged-pointer / inlined / out-of-line representation; UTF-8 backing. |
Optional<Wrapped> |
stdlib/public/core/Optional.swift |
Two-case enum; spelled as ?/! in the language. |
Sequence |
stdlib/public/core/Sequence.swift |
Once-iterable. |
Collection |
stdlib/public/core/Collection.swift |
Indexed, multi-pass. |
Hashable |
stdlib/public/core/Hashable.swift |
Protocol; uses Hasher (Wyhash-based). |
Hasher |
stdlib/public/core/Hasher.swift |
Universal hasher, seeded from _swift_stdlib_Hashing_parameters. |
KeyPath |
stdlib/public/core/KeyPath.swift |
Encoding of property paths. Runtime support in stdlib/public/runtime/KeyPaths.cpp. |
Hasher, AnyHashable, AnyKeyPath |
stdlib/public/core/AnyHashable.swift |
Type-erased variants. |
How it works
Generic protocol hierarchy
The protocol hierarchy is the heart of the standard library:
graph BT
Equatable --> Hashable
Equatable --> Comparable
Sequence --> Collection
Collection --> BidirectionalCollection
BidirectionalCollection --> RandomAccessCollection
Collection --> MutableCollection
Collection --> RangeReplaceableCollection
IteratorProtocol -.- SequenceMost concrete types Array, String, Set, Dictionary, ContiguousArray, ArraySlice, Range, ClosedRange participate by conforming to multiple of these.
String representation
String uses a tagged 16-byte representation (the _StringObject): a pointer plus discriminator bits that select between (a) a small inline string up to 15 UTF-8 bytes, (b) a literal pointer to an immortal string, (c) a pointer to a heap-allocated buffer, or (d) a bridged NSString. Implementation in String.swift, StringObject.swift, StringStorage.swift, StringBridge.swift, StringComparable.swift, etc. Unicode normalization data is generated into the giant stubs/Unicode/...ScalarPropsData.h headers.
Array representation
Array<Element> is a struct holding a pointer to a _ContiguousArrayStorage<Element> (or __SwiftDeferredNSArray on Apple platforms when bridged). COW (copy-on-write) is implemented manually via uniqueness checks (isKnownUniquelyReferenced, _swift_isUniquelyReferenced_native). On Apple, Array<NSObject>-shaped arrays can be backed by an NSArray directly; see ArrayBuffer.swift, ContiguousArrayBuffer.swift, ArrayCast.swift.
Dictionary and Set
Both use the same open-addressing hash table with quadratic probing. The hash table layout is in _NativeSet.swift and _NativeDictionary.swift (under Set.swift, Dictionary.swift). The hasher is universal and seeded per-process; SWIFT_DETERMINISTIC_HASHING=1 overrides the seed for reproducible bug reports.
Codable
Defined in Codable.swift. Provides the Encodable / Decodable protocols and the synthesized conformance machinery. Concrete encoders (JSONEncoder, PropertyListEncoder) live in the Foundation repo, not here.
gyb templates
The numeric stack is large and uniform: Int8 ... Int64, UInt8 ... UInt64, Float, Double, Float80 (where supported), Float16. Rather than hand-writing 200+ overloads, Integers.swift.gyb, FloatingPointTypes.swift.gyb, Tuple.swift.gyb, AtomicInt.swift.gyb and others use the gyb templating tool. Build runs gyb per .gyb file at configure time.
Builtin module
Builtin.swift re-exports the magic Builtin.* operations (Builtin.add_Int64, Builtin.allocRaw, Builtin.lookupOptional, ...) as @_transparent wrappers. These are the lowest-level ops; SILGen recognizes calls to them and lowers them directly to SIL instructions.
Integration points
- The compiler -- a working stdlib must exist before any non-stdlib Swift compiles. The
swift-frontendfinds it via-resource-dir. - The runtime -- many stdlib types call into
stdlib/public/runtime/for allocation, casting, metadata. The runtime in turn calls back into stdlib for things likeStringformatting (the runtime cannot importSwift, but the C++ implementation pretends to know the layouts). - Overlays --
Foundation,XCTest,Dispatch, etc. extend the stdlib with platform APIs; they live in swift-corelibs-foundation, swift-corelibs-libdispatch, swift-corelibs-xctest. - C++ interop uses the
Cxxoverlay (stdlib/public/Cxx/) to bridgestd::string,std::vector, etc.
Resilience
Most public stdlib API is @usableFromInline/@inlinable for generic specialization. ABI-stable types are @frozen (locking layout). New API is often gated behind @_alwaysEmitIntoClient so it can ship to clients targeting older runtimes without the runtime needing to upgrade. See docs/LibraryEvolution.rst and docs/StandardLibraryProgrammersManual.md.
Entry points for modification
- Adding a new overload to
Array,String, etc.: edit the corresponding.swiftfile. Add tests intest/stdlib/. If the API is user-facing, you also need a Swift Evolution proposal. - Optimizing a stdlib hot path: profile with the
benchmark/suite. Compile with-Xllvm -sil-print-after=GenericSpecializerto see how it specializes. - Working around a runtime limitation:
@_alwaysEmitIntoClientlets you ship API to older OSes (the implementation is inlined into client binaries).
Related pages
- Runtime -- the C/C++ partner.
- Concurrency -- the
_Concurrencymodule. - Patterns and conventions -- stdlib coding conventions.
docs/StdlibAPIGuidelines.rst-- the API style guide.
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.
Previous
Libraries
Next
Concurrency