Array
public struct Array[T] { /* private fields */ }A dynamic, growable, contiguous-buffer array with copy-on-write storage.
Array[T] is the standard ordered-collection type. It supports
constant-time random access, amortized constant-time append, and
arbitrary-position insert/remove via shifting. Storage is shared between
copies until one of them mutates, at which point that copy lazily clones
the buffer (see "Memory Model" below). For non-owning views over an
existing buffer use ArraySlice[T]; for fixed-size or set-like collections
see ArraySlice[T], Set, or Dictionary.
Examples
let evens = [2, 4, 6, 8];
var names = Array[String]();
names.append("Alice");
names.append("Bob");
let copy = names; // O(1) — shares storage with `names`
names.append("Carol"); // O(1) clone happens here, `copy` is unchanged
for n in names.iter() { ... }
let pivot = names.partition(by: { (n) in n.count > 3 });
Indexing
The default subscript arr(i) panics on out-of-bounds. Variants exist
for every common policy: arr(checked: i) returns T?,
arr(unchecked: i) skips the bounds check (UB on OOB),
arr(wrapped: i) wraps with modulo (and supports negative indices),
and arr(clamped: i) clamps to [0, count-1]. Range arguments use the
same labels — arr(0..<3), arr(checked: r), arr(unchecked: r),
arr(clamped: r) — dispatched through the unified SeqIndex[T],
SeqClampable[T], and SeqWrappable[T] protocols. Int64 and range
types share each label; the result type varies (T? vs ArraySlice[T]
for clamped:).
Capacity & Reallocation
count is the number of elements; capacity is how many can fit
without reallocating. When append would exceed capacity the buffer
doubles (starting from 4 if previously zero). Use
reserveCapacity(minimumCapacity:) to pre-allocate, and
shrinkToFit() to release excess.
Representation
Holds a single CowBox[ArrayStorage[T]] field. The storage is a
(ptr, len, cap) triple over a heap-allocated buffer.
Memory Model
Reference-counted storage with copy-on-write value semantics. Copying
an Array is O(1) and shares the buffer; the next mutation on a shared
Array triggers makeUnique(), which deep-clones the buffer so the
mutation is invisible to other copies. The user-visible behavior is
indistinguishable from deep-copying on assignment.
Guarantees
- Elements are stored contiguously and are accessible via
asPointer()for FFI; the pointer is invalidated by any mutation that may reallocate. count <= capacityalways.- Iteration order is insertion order.
- Operations marked O(1) are amortized; growth is geometric.
Properties
public var capacity: Int64 { get }
public var capacity: Int64 { get }The number of elements the buffer can hold without reallocating.
Initializers
public init(arrayLiteral: LiteralSlice[T])
public init(arrayLiteral: LiteralSlice[T])Creates an array containing every element of the supplied literal slice.
Allocates a buffer sized exactly to the literal's element count
(so capacity == count after construction) and copies the
elements over. An empty slice yields an empty unallocated array.
Panics if allocation fails.
Examples
// Triggered by the array-literal syntax:
let arr: Array[Int64] = [10, 20, 30];public init()
public init()Creates an empty array with no allocation.
Capacity starts at zero; the first append allocates a small
buffer (currently 4 elements). Use init(capacity:) if you can
pre-size to avoid the early growth steps.
Examples
var arr = Array[Int64]();
arr.count; // 0
arr.capacity; // 0public init(of: Int64, generatedBy: (Int64) -> T)
public init(of: Int64, generatedBy: (Int64) -> T)Creates an array of count elements computed by a per-index closure.
Allocates exactly count slots and invokes gen(i) once for each
i in 0..<count. count <= 0 produces an empty array. Use this
when each slot is a function of its index; for a constant value,
prefer init(repeating:count:).
Examples
let squares = Array(of: 5, generatedBy: { (i) in i * i }); // [0, 1, 4, 9, 16]
let indices = Array(of: 3, generatedBy: { (i) in i }); // [0, 1, 2]
let empty = Array(of: 0, generatedBy: { (i) in i }); // []public init[I](from: I) where I: Iterable, I.Item == T
public init[I](from: I) where I: Iterable, I.Item == TCreates an array by collecting every element produced by an iterable.
Drains iterable to completion via append, so the resulting
capacity is whatever the growth policy lands on (not necessarily
equal to count). For a sized source you can shave reallocations
by following with shrinkToFit(). See also append(from:)
to add elements to an existing array.
Examples
let fromRange = Array(from: 1..<5); // [1, 2, 3, 4]
let fromSet = Array(from: mySet); // arbitrary order
let collected = Array(from: lines.iter()); // exhausts the iteratorinit(storage: CowBox[ArrayStorage[T]])
init(storage: CowBox[ArrayStorage[T]])Wraps an existing storage box in a new Array.
Module-internal — used by clone(), ArrayBuilder.build(), and
other std.collections code that constructs arrays from raw
storage.
public init(_arrayLiteralPointer: consuming lang.ptr[T], _arrayLiteralCount: consuming lang.i64)
public init(_arrayLiteralPointer: consuming lang.ptr[T], _arrayLiteralCount: consuming lang.i64)Compiler-emitted bridge initializer for [a, b, c] array literals.
Not called by user code directly — the parser lowers literal
expressions into a (ptr, count) pair which this constructor wraps
in a LiteralSlice and forwards to init(arrayLiteral:).
Safety
The compiler guarantees _arrayLiteralPointer points to exactly
_arrayLiteralCount initialized elements of T.
Examples
let arr = [1, 2, 3]; // emitted by the compiler as a call to this init
public init(repeating: T, count: Int64)
public init(repeating: T, count: Int64)Creates an array of count identical copies of value.
Allocates exactly count slots and writes the same value into each.
count <= 0 produces an empty array. Useful for initializing
fixed-size buffers; if you instead want each slot computed, use
init(count:generator:).
Examples
let zeros = Array(repeating: 0, count: 5); // [0, 0, 0, 0, 0]
let empty = Array(repeating: "x", count: 0); // []
let pad = Array(repeating: " ", count: 3); // [" ", " ", " "]public init(capacity: Int64)
public init(capacity: Int64)Creates an empty array with at least the requested capacity reserved.
Equivalent to Array() followed by reserveCapacity(...), but
done in a single allocation. A non-positive capacity behaves
like init() (no allocation). Panics if allocation fails.
Examples
var arr = Array[Int64](capacity: 1000);
arr.count; // 0
arr.capacity; // >= 1000 — no reallocation for first 1000 appendsMethods
public mutating func append(consuming T)
public mutating func append(consuming T)Appends element to the end of the array.
Amortized O(1). Triggers a reallocation (and COW if storage is
shared) when count == capacity. For appending many elements,
reserveCapacity(...) first to avoid intermediate growths; for
adding multiple elements at once see append(contentsOf:) or
append(from:).
Examples
var arr = [1, 2];
arr.append(3); // [1, 2, 3]public mutating func append[__opaque_0](contentsOf: __opaque_0) where __opaque_0: Slice[T]
public mutating func append[__opaque_0](contentsOf: __opaque_0) where __opaque_0: Slice[T]Appends every element of other to the end of this array.
Reserves the exact required capacity in one growth step then
copies the elements over, so it's faster than calling append
in a loop. Sharing semantics: other is read-only here, but if
self shares storage with anything else, COW fires once at the
start. See also append(from:) for arbitrary iterable
sources.
Examples
var arr = [1, 2];
arr.append(contentsOf: [3, 4]); // [1, 2, 3, 4]
arr.append(contentsOf: []); // [1, 2, 3, 4] — no-oppublic mutating func append[I](from: I) where I: Iterable, I.Item == T
public mutating func append[I](from: I) where I: Iterable, I.Item == TAppends every element produced by an arbitrary iterable.
Drains the iterable via append, so capacity grows geometrically
rather than to an exact target — for sized sources like another
Array, prefer append(contentsOf:).
Examples
var arr = [1, 2];
arr.append(from: 3..<6); // [1, 2, 3, 4, 5]public func atProbe(index: Int64) -> T
public func atProbe(index: Int64) -> TIn-place element access (stage-1.5 place accessors): reads borrow
the element — no copy, no clone, no T: Cloneable requirement —
and writes, +=, and mutating methods go through the element's
address. Binding the read (let x = arr(at: i)) stores an owned
copy instead (binding decay). Panics if out of bounds, like
arr(index).
The mutating accessor ensures unique (COW) storage BEFORE the
place is fabricated, so writes through it never touch a sibling
copy's buffer. Copying self inside the same expression that
uses the place (f(arr(at: 0), arr) with a mutating first arg)
re-shares the buffer and can make the write observable through
the copy — accepted stage-1 behavior, recorded in the references
semantics.
The unlabeled subscripts (arr(i), arr(1..<3), checked:,
unchecked:, clamped:, wrapped:) live on extend Slice[T]
and keep get/set semantics; at: is the labeled in-place form.
public mutating func clear()
public mutating func clear()Removes every element from the array, leaving capacity untouched.
O(1). The buffer is kept so subsequent appends don't reallocate
— if you want the memory back, follow with shrinkToFit().
Examples
var arr = [1, 2, 3];
arr.clear(); // arr is []
arr.capacity; // unchangedpublic mutating func dedup()
public mutating func dedup()Removes runs of consecutive equal elements, in place.
Only adjacent duplicates collapse — non-adjacent equal values are
kept. To deduplicate globally, sort() first or, for Hashable
elements, use the unique() / removeDuplicates() extension
methods. The non-mutating variant is deduped().
Examples
var arr = [1, 1, 2, 2, 2, 3, 1, 1];
arr.dedup(); // [1, 2, 3, 1] — trailing 1s survive (not adjacent to first run)public func deduped() -> Array[T]
public func deduped() -> Array[T]Returns a new array with consecutive duplicates removed; original is unchanged.
Non-mutating mirror of dedup(). Same caveat: only adjacent
duplicates collapse.
Examples
[1, 1, 2, 2, 3].deduped(); // [1, 2, 3]
[1, 2, 1, 2].deduped(); // [1, 2, 1, 2] — none are adjacentpublic func flatten() -> Array[T.Item]
public func flatten() -> Array[T.Item]Concatenates each element's iterator into a single
Array[T.Item].
Drains every inner iterator in order. Empty inner sequences
disappear without affecting the surrounding ones. Element type
of the result is T.Item, the inner iterable's item type.
Examples
let nested = [[1, 2], [3, 4], [5]];
nested.flatten(); // [1, 2, 3, 4, 5]
let mixed = [[1], [], [2, 3]];
mixed.flatten(); // [1, 2, 3]public mutating func insert(T, at: Int64)
public mutating func insert(T, at: Int64)Inserts element at index, shifting later elements right by one.
O(n) in the number of elements after index. index == count
behaves like append. Triggers COW and may reallocate. For bulk
insertion at one location, prefer
replaceSubrange(i..<i, with: ...).
Errors
Panics with "Array.insert: index out of bounds" if index < 0
or index > count.
Examples
var arr = [1, 3];
arr.insert(2, at: 1); // [1, 2, 3]
arr.insert(0, at: 0); // [0, 1, 2, 3]
arr.insert(4, at: 4); // [0, 1, 2, 3, 4] — append-equivalent
arr.insert(9, at: 99); // PANICpublic func joined(String) -> String
public func joined(String) -> StringConcatenates each element's string representation, separated by
separator.
Each element is rendered with its format() method using default
FormatOptions. The default separator is empty (raw
concatenation). Empty arrays produce "". For the bracketed
debug form ("[1, 2, 3]"), use format() directly.
Examples
[1, 2, 3].joined(", "); // "1, 2, 3"
[1, 2, 3].joined(); // "123"
["a", "b"].joined("-"); // "a-b"
[].joined(", "); // ""public mutating func mutableRefs() -> MutRefSliceIterator[T]
public mutating func mutableRefs() -> MutRefSliceIterator[T]Returns an iterator yielding MUTABLE REFERENCES (&mutating T)
to the elements — in-place mutation without writeback. Runs the
COW barrier first, so writes never leak into shared storage.
Structural mutation (append, removal) during iteration
invalidates the yielded references.
Examples
var xs = [1, 2, 3];
for x in xs.mutableRefs() {
x += 1;
}
// xs == [2, 3, 4]public mutating func partition(by: (T) -> Bool) -> Int64
public mutating func partition(by: (T) -> Bool) -> Int64Reorders elements in place so that all matching elements come before all non-matching elements; returns the partition point.
The returned index is the count of matching elements (and the
index of the first non-matching one). This is an unstable
partition — relative order within each side is not preserved.
For a stable, allocating variant that returns two arrays, use
partitioned(by:).
Examples
var arr = [1, 2, 3, 4, 5];
let pivot = arr.partition(by: { (x) in x % 2 == 0 });
// arr might be [2, 4, 3, 1, 5] (or another valid permutation)
// pivot == 2 — first two elements satisfy the predicatepublic func partitioned(by: (T) -> Bool) -> (Array[T], Array[T])
public func partitioned(by: (T) -> Bool) -> (Array[T], Array[T])Returns two new arrays: elements matching predicate first, then
elements that don't.
Stable: relative order within each side is preserved. Allocates
two new arrays — use partition(by:) for an in-place, unstable
reordering that avoids the allocation.
Examples
let (evens, odds) = [1, 2, 3, 4, 5].partitioned(by: { (x) in x % 2 == 0 });
// evens = [2, 4]
// odds = [1, 3, 5]public mutating func pop() -> T?
public mutating func pop() -> T?Removes and returns the last element, or None if the array is empty.
O(1). Capacity is retained for reuse — only len is decremented.
The mirror operation popFirst() is O(n) because it must shift
the remainder. To inspect the last element without removing, use
last().
Examples
var arr = [1, 2, 3];
arr.pop(); // Some(3), arr is [1, 2]
arr.pop(); // Some(2), arr is [1]
arr.pop(); // Some(1), arr is []
arr.pop(); // None, arr is still []public mutating func popFirst() -> T?
public mutating func popFirst() -> T?Removes and returns the first element, or None if the array is
empty.
O(n) — every following element shifts left by one. If you can
tolerate it, pop() from the back is O(1). For inspection
without removal, use first().
Examples
var arr = [1, 2, 3];
arr.popFirst(); // Some(1), arr is [2, 3]
arr.popFirst(); // Some(2), arr is [3]public func refs() -> RefSliceIterator[T]
public func refs() -> RefSliceIterator[T]Returns an iterator yielding SHARED REFERENCES (&T) to the
elements in place — no copies, no clones. References are
read-only views; they alias the array's buffer, so structural
mutation (append, removal) during iteration invalidates them.
Examples
let words = ["alpha", "beta"];
for w in words.refs() {
print(w.len()); // reads in place — no element copy
}public mutating func remove(at: Int64) -> T
public mutating func remove(at: Int64) -> TRemoves and returns the element at index, shifting later
elements left.
O(n - index). Capacity is retained. For removing many elements at
once, prefer removeSubrange(range:). To remove the first
element by value see the Equatable extension's
remove(element:).
Errors
Panics with "Array.remove: index out of bounds" if index < 0
or index >= count.
Examples
var arr = [1, 2, 3, 4];
arr.remove(at: 1); // returns 2; arr is [1, 3, 4]
arr.remove(at: 9); // PANICpublic mutating func remove(T) -> Bool
public mutating func remove(T) -> BoolRemoves the first element equal to element. Returns whether a
removal occurred.
Performs firstIndex(of:) then remove(at:). To strip every
occurrence in one pass, use removeAll(element:).
Examples
var arr = [1, 2, 3, 2];
arr.remove(2); // true; arr is [1, 3, 2]
arr.remove(5); // false; arr unchangedpublic mutating func removeAll(where: consuming (T) -> Bool)
public mutating func removeAll(where: consuming (T) -> Bool)Removes every element for which predicate returns true.
The inverse of retain(where:) — implemented as
retain over the negated predicate. O(n), stable.
Examples
var arr = [1, 2, 3, 4, 5];
arr.removeAll(where: { (x) in x % 2 == 0 }); // [1, 3, 5]
var names = ["Alice", "", "Bob", ""];
names.removeAll(where: { (s) in s.isEmpty }); // ["Alice", "Bob"]public mutating func removeAll(T)
public mutating func removeAll(T)Removes every element equal to element.
Implemented as retain with a negated equality predicate —
O(n), single pass, stable. To remove only the first occurrence
use remove(element:).
Examples
var arr = [1, 2, 3, 2, 4, 2];
arr.removeAll(2); // [1, 3, 4]public mutating func removeDuplicates()
public mutating func removeDuplicates()Removes every duplicate in place, keeping the first occurrence.
Implemented by replacing storage with the result of unique(),
so the same O(n²) caveat applies. The non-mutating mirror is
unique().
Examples
var arr = [1, 2, 1, 3, 2];
arr.removeDuplicates(); // [1, 2, 3]public mutating func removeSubrange[R](R) where R: SeqRange
public mutating func removeSubrange[R](R) where R: SeqRangeRemoves every element in range, shifting later elements left.
O(count - range.end + range.length). Empty ranges are no-ops.
Capacity is retained — call shrinkToFit() to release it. For
"remove these and put others back" use replaceSubrange(...).
Errors
Panics with "Array.removeSubrange: range out of bounds" if
range.start < 0, range.end > count, or
range.start > range.end.
Examples
var arr = [1, 2, 3, 4, 5];
arr.removeSubrange(1..<4); // arr is [1, 5]
arr.removeSubrange(0..<0); // no-oppublic mutating func replaceSubrange[R](R, with: Array[T]) where R: SeqRange
public mutating func replaceSubrange[R](R, with: Array[T]) where R: SeqRangeReplaces the elements in range with the elements of replacement.
replacement.count need not equal the range length — the array
shrinks or grows accordingly, shifting the trailing elements once.
Use range == i..<i to insert without removing, or
replacement == [] to remove without inserting (equivalent to
removeSubrange(...)). May reallocate; triggers COW.
Errors
Panics with "Array.replaceSubrange: range out of bounds" if
range.start < 0, range.end > count, or
range.start > range.end.
Examples
var arr = [1, 2, 3, 4, 5];
arr.replaceSubrange(1..<4, with: [20, 30]); // [1, 20, 30, 5]
arr.replaceSubrange(1..<1, with: [9, 9]); // insert: [1, 9, 9, 20, 30, 5]
arr.replaceSubrange(0..<2, with: Array[Int64]()); // remove: [9, 20, 30, 5]public mutating func reserveCapacity(Int64)
public mutating func reserveCapacity(Int64)Reserves enough capacity to hold at least minimumCapacity elements.
A no-op when capacity already suffices. The actual capacity after
the call may exceed the request because growth rounds up via the
doubling policy. Pair with bulk inserts to skip intermediate
reallocations. The opposite operation is shrinkToFit().
Examples
var arr = Array[Int64]();
arr.reserveCapacity(1000);
for i in 0..<1000 {
arr.append(i); // no reallocations
}public mutating func retain(where: (T) -> Bool)
public mutating func retain(where: (T) -> Bool)Keeps only elements for which predicate returns true; removes
the rest in place.
O(n), single pass, stable (relative order preserved). The mirror
operation is removeAll(where:). For a copy instead of an
in-place edit, use iter().filter(...).collect().
Examples
var arr = [1, 2, 3, 4, 5];
arr.retain(where: { (x) in x % 2 == 0 }); // [2, 4]public mutating func reverse()
public mutating func reverse()Reverses the order of elements in place.
O(n). Triggers COW. For a non-mutating variant returning a new
array, use reversed().
Examples
var arr = [1, 2, 3];
arr.reverse(); // [3, 2, 1]public mutating func rotate(by: Int64)
public mutating func rotate(by: Int64)Rotates the elements in place by amount positions to the left.
Implemented with the three-reversal algorithm — O(n) time,
O(1) extra space. Negative amount rotates right; the actual
rotation is amount mod count, so very large amounts wrap. A
no-op when count <= 1 or the normalized amount is zero.
Examples
var arr = [1, 2, 3, 4, 5];
arr.rotate(by: 2); // [3, 4, 5, 1, 2]
arr.rotate(by: -1); // [2, 3, 4, 5, 1]
arr.rotate(by: 7); // same as rotate(by: 2) for count == 5public mutating func shrinkToFit()
public mutating func shrinkToFit()Releases unused capacity by reallocating to fit count exactly.
Useful after a bulk removal or when you've finished building a
large array. A no-op when capacity == count. For an empty
array, fully deallocates the buffer (capacity drops to 0).
Triggers COW.
Examples
var arr = Array[Int64](capacity: 1000);
arr.append(1);
arr.shrinkToFit(); // capacity reduced to 1
arr.clear();
arr.shrinkToFit(); // capacity reduced to 0, buffer freedpublic mutating func shuffle[__opaque_0](using: __opaque_0) where __opaque_0: RandomNumberGenerator
public mutating func shuffle[__opaque_0](using: __opaque_0) where __opaque_0: RandomNumberGeneratorShuffles the array in place using rng.
Uses the Fisher-Yates algorithm — every permutation is equally
likely, given a uniform RNG. Passing the same seeded rng
produces a deterministic shuffle, which is the usual reason to
reach for this overload over the no-arg shuffle().
Examples
var arr = [1, 2, 3, 4, 5];
var rng = Lcg64(seed: 42);
arr.shuffle(using: rng); // deterministic for the seedpublic mutating func shuffle()
public mutating func shuffle()Shuffles the array in place using a fresh default RNG.
Convenience over shuffle(using:). The result is non-deterministic
across calls — pass an explicit Lcg64(seed: ...) (or other
RandomNumberGenerator) when you need reproducibility.
Examples
var arr = [1, 2, 3, 4, 5];
arr.shuffle(); // e.g. [3, 1, 5, 2, 4]public func shuffled[__opaque_0](using: __opaque_0) -> Array[T] where __opaque_0: RandomNumberGenerator
public func shuffled[__opaque_0](using: __opaque_0) -> Array[T] where __opaque_0: RandomNumberGeneratorReturns a new array shuffled with rng. The original is unchanged.
The non-mutating mirror of shuffle(using:). Internally clones via
COW (cheap until the next mutation) and shuffles the copy.
Examples
let arr = [1, 2, 3, 4, 5];
var rng = Lcg64(seed: 42);
let result = arr.shuffled(using: rng);
// arr is still [1, 2, 3, 4, 5]public func shuffled() -> Array[T]
public func shuffled() -> Array[T]Returns a new array shuffled with a default RNG. Original unchanged.
Convenience over shuffled(using:). Non-deterministic between
calls.
Examples
let arr = [1, 2, 3, 4, 5];
let shuffled = arr.shuffled(); // e.g. [4, 2, 5, 1, 3]
// arr is still [1, 2, 3, 4, 5]public mutating func sort()
public mutating func sort()Sorts the array in ascending order using the natural < ordering.
Uses introsort — O(n log n) worst-case. For descending or custom
orderings pass a comparator to sort(by:). Non-mutating variant:
sorted().
Examples
var arr = [3, 1, 4, 1, 5];
arr.sort(); // [1, 1, 3, 4, 5]public mutating func sort(by: (T, T) -> Bool)
public mutating func sort(by: (T, T) -> Bool)Sorts the array in place using a <-style comparator.
The comparator returns true when its first argument should come
before the second. Uses introsort — quicksort with heapsort
fallback when recursion exceeds 2·log₂(n), and insertion sort for
partitions ≤ 16 elements. O(n log n) worst-case. Pass a reversed
comparator for descending order.
Examples
var arr = [1, 5, 3, 2, 4];
arr.sort(by: { (a, b) in a > b }); // [5, 4, 3, 2, 1] descendingpublic mutating func sort[K](byKey: consuming (T) -> K) where K: Comparable
public mutating func sort[K](byKey: consuming (T) -> K) where K: ComparableSorts the array in place by an extracted Comparable key.
Examples
var people = [Person("Alice", 30), Person("Bob", 25)];
people.sort(byKey: { (p) in p.age });public func sorted(by: (T, T) -> Bool) -> Array[T]
public func sorted(by: (T, T) -> Bool) -> Array[T]Returns a new array sorted by a custom comparator. Original unchanged.
Examples
let arr = [3, 1, 2];
let desc = arr.sorted(by: { (a, b) in a > b }); // [3, 2, 1]public func sorted[K](byKey: consuming (T) -> K) -> Array[T] where K: Comparable
public func sorted[K](byKey: consuming (T) -> K) -> Array[T] where K: ComparableReturns a new array sorted by an extracted Comparable key;
original unchanged.
Examples
let words = ["hi", "hello", "hey"];
let byLen = words.sorted(byKey: { (w) in w.count });public mutating func swap(at: Int64, with: Int64)
public mutating func swap(at: Int64, with: Int64)Swaps the elements at indices i and j in place.
O(1). A no-op when i == j. Triggers COW.
Errors
Panics with "Array.swap: index out of bounds" if either index
is < 0 or >= count.
Examples
var arr = [1, 2, 3];
arr.swap(at: 0, with: 2); // [3, 2, 1]
arr.swap(at: 1, with: 1); // [3, 2, 1] — no-op
arr.swap(at: 0, with: 9); // PANICSubscripts
public subscript(at: Int64) -> T { ref mutating ref }
public subscript(at: Int64) -> T { ref mutating ref }ImplementsSlice
Properties
public var count: Int64 { get }
public var count: Int64 { get }Element count. O(1).
Examples
[1, 2, 3].count; // 3
[].count; // 0public var indices: Range[Int64] { get }
public var indices: Range[Int64] { get }Half-open range 0..<count.
Examples
[10, 20, 30].indices; // 0..<3
public var isEmpty: Bool { get }
public var isEmpty: Bool { get }true when count == 0.
Examples
[].isEmpty; // true
[1].isEmpty; // falseMethods
public func all(where: (T) -> Bool) -> Bool
public func all(where: (T) -> Bool) -> Booltrue when every element satisfies predicate. O(n).
Short-circuits on the first failure. Vacuously true for empty collections.
Examples
[2, 4, 6].all(where: { it % 2 == 0 }); // true
[2, 3, 6].all(where: { it % 2 == 0 }); // falsepublic func any(where: (T) -> Bool) -> Bool
public func any(where: (T) -> Bool) -> Booltrue when at least one element satisfies predicate. O(n).
Short-circuits on the first match. Always false for empty
collections.
Examples
[1, 2, 3].any(where: { it > 2 }); // true
[1, 2, 3].any(where: { it > 5 }); // falsepublic func asPointer() -> Pointer[T]
public func asPointer() -> Pointer[T]Pointer to the first element. The pointer aliases the collection's buffer; do not outlive the source or mutate through it.
Safety
Reading past count is undefined behavior.
public func asSlice() -> ArraySlice[T]
public func asSlice() -> ArraySlice[T]Slice protocol kernel — borrows the array's buffer as an ArraySlice.
public func binarySearch(T) -> Int64?
public func binarySearch(T) -> Int64?Binary search for element. Returns its index or None. O(log n).
When duplicates exist, which index is returned is unspecified.
Safety
The collection must be sorted in ascending order. Calling on unsorted data won't crash but may produce false negatives.
Examples
[1, 2, 3, 4, 5].binarySearch(3); // Some(2)
[1, 2, 3, 4, 5].binarySearch(6); // Nonepublic func chunks(of: Int64) -> ChunksView[T]
public func chunks(of: Int64) -> ChunksView[T]Multi-pass lazy view over non-overlapping size-sized chunks.
The trailing chunk may be shorter than size. Multi-pass: query
count, index with view.get(i), and iterate repeatedly without
re-creating the view.
Errors
Panics if size <= 0.
Examples
let v = [1, 2, 3, 4, 5].chunks(of: 2);
v.count; // 3
v.get(2); // ArraySlice[5]
for c in v { ... }public func compactMap[U]((T) -> Optional[U]) -> Array[U]
public func compactMap[U]((T) -> Optional[U]) -> Array[U]Maps every element through transform, dropping .None results.
O(n).
Examples
["1", "x", "3"].compactMap { Int64.parse(it) }; // [1, 3]
public func contains(T) -> Bool
public func contains(T) -> Booltrue if the collection contains element. O(n).
Linear scan; short-circuits on the first match.
Examples
[1, 2, 3].contains(2); // true
[1, 2, 3].contains(5); // falsepublic func countItems(where: (T) -> Bool) -> Int64
public func countItems(where: (T) -> Bool) -> Int64Number of elements for which predicate is true. O(n).
Examples
[1, 2, 3, 4, 5].countItems(where: { it % 2 == 0 }); // 2
public func drop(first: Int64) -> ArraySlice[T]
public func drop(first: Int64) -> ArraySlice[T]Returns a slice with the first count elements skipped. O(1).
Complement of prefix.
Errors
Panics if count > self.count.
Examples
[1, 2, 3, 4, 5].drop(first: 2); // ArraySlice[3, 4, 5]
public func ends[__opaque_0](with: __opaque_0) -> Bool where __opaque_0: Slice[T]
public func ends[__opaque_0](with: __opaque_0) -> Bool where __opaque_0: Slice[T]true if the trailing elements match suffix. O(k) where k is
the suffix length. Accepts any Slice[T] conformer.
Examples
[1, 2, 3].ends(with: [2, 3]); // true
[1, 2, 3].ends(with: [1, 2]); // false
[1, 2, 3].ends(with: []); // true (vacuous)public mutating func ensureUnique()
public mutating func ensureUnique()COW write barrier — deep-copies storage if shared.
public func filter(where: (T) -> Bool) -> Array[T]
public func filter(where: (T) -> Bool) -> Array[T]Returns a new array containing every element matching predicate.
O(n). Result size is unknown; uses geometric growth.
Examples
[1, 2, 3, 4].filter(where: { it % 2 == 0 }); // [2, 4]
public func first() -> T?
public func first() -> T?First element, or .None for an empty collection. O(1).
Read-only — to remove the first element from an Array, use
popFirst().
Examples
[1, 2, 3].first(); // Some(1)
[].first(); // Nonepublic func firstIndex(where: (T) -> Bool) -> Int64?
public func firstIndex(where: (T) -> Bool) -> Int64?Index of the first element matching predicate, or None. O(n).
Short-circuits on the first match. For value-based search on
Equatable collections, use firstIndex(of:).
Examples
[1, 2, 3, 4, 5].firstIndex(where: { it > 3 }); // Some(3)
[1, 2, 3].firstIndex(where: { it > 10 }); // Nonepublic func flatMap[U]((T) -> Array[U]) -> Array[U]
public func flatMap[U]((T) -> Array[U]) -> Array[U]Maps every element through transform and concatenates the results
into one flat array. O(n + total_output).
Examples
[1, 2, 3].flatMap { [it, it * 10] }; // [1, 10, 2, 20, 3, 30]
public func format(into: mutating StringBuilder, FormatOptions)
public func format(into: mutating StringBuilder, FormatOptions)Renders as "[e1, e2, ...]". Empty collections render as "[]".
Examples
[1, 2, 3].format(); // "[1, 2, 3]"
[].format(); // "[]"public func isEqual(to: Self) -> Bool
public func isEqual(to: Self) -> BoolElement-wise equality. O(n).
Short-circuits on the first mismatch. Order matters.
Examples
[1, 2, 3].isEqual(to: [1, 2, 3]); // true
[1, 2, 3].isEqual(to: [3, 2, 1]); // falsepublic func isSorted() -> Bool
public func isSorted() -> Booltrue if elements are in non-decreasing order. O(n).
Equal adjacent elements are allowed. Empty and single-element collections are vacuously sorted.
Examples
[1, 2, 3].isSorted(); // true
[1, 3, 2].isSorted(); // false
[1, 1, 1].isSorted(); // true
[].isSorted(); // truepublic func isValidIndex(Int64) -> Bool
public func isValidIndex(Int64) -> Booltrue if index is in [0, count).
Examples
[10, 20, 30].isValidIndex(2); // true
[10, 20, 30].isValidIndex(3); // false
[10, 20, 30].isValidIndex(-1); // falsepublic func iter() -> ArraySliceIterator[T]
public func iter() -> ArraySliceIterator[T]Forward iterator over the elements.
Examples
for item in [1, 2, 3] { ... }
public func last() -> T?
public func last() -> T?Last element, or .None for an empty collection. O(1).
Read-only — to remove the last element from an Array, use
pop().
Examples
[1, 2, 3].last(); // Some(3)
[].last(); // Nonepublic func lastIndex(where: (T) -> Bool) -> Int64?
public func lastIndex(where: (T) -> Bool) -> Int64?Index of the last element matching predicate, or None. O(n).
Scans from the back; short-circuits on the first match.
Examples
[1, 2, 3, 2, 1].lastIndex(where: { it == 2 }); // Some(3)
public func map[U]((T) -> U) -> Array[U]
public func map[U]((T) -> U) -> Array[U]Maps every element through transform into a new array. O(n).
Pre-sizes the result buffer to self.count, so no growth steps. For
the lazy version that fuses into a chain, use iter().map { ... }.
Examples
[1, 2, 3].map { it * 2 }; // [2, 4, 6]
[1, 2, 3].map { it.format() }; // ["1", "2", "3"]public func max() -> T?
public func max() -> T?Largest element, or None if empty. O(n).
Ties go to the first occurrence.
Examples
[3, 1, 4].max(); // Some(4)
[].max(); // Nonepublic func min() -> T?
public func min() -> T?Smallest element, or None if empty. O(n).
Ties go to the first occurrence.
Examples
[3, 1, 4].min(); // Some(1)
[].min(); // Nonepublic func prefix(Int64) -> ArraySlice[T]
public func prefix(Int64) -> ArraySlice[T]Returns a slice over the first count elements. O(1).
Errors
Panics if count > self.count.
Examples
[1, 2, 3, 4, 5].prefix(3); // ArraySlice[1, 2, 3]
[1, 2].prefix(0); // empty slicepublic func reversed() -> ReversedView[T]
public func reversed() -> ReversedView[T]Multi-pass lazy reversed view. Iterates back-to-front and supports indexed access in O(1).
Examples
let v = [1, 2, 3].reversed();
v.first(); // Some(3)
v.toArray(); // [3, 2, 1] — eager copypublic func sorted() -> Array[T]
public func sorted() -> Array[T]Returns a new sorted array; original unchanged. O(n log n).
Examples
let arr = [3, 1, 4, 1, 5];
arr.sorted(); // [1, 1, 3, 4, 5]
// arr is still [3, 1, 4, 1, 5]public func split(where: consuming (T) -> Bool) -> ArraySplitWhereView[T]
public func split(where: consuming (T) -> Bool) -> ArraySplitWhereView[T]Multi-pass lazy view over the segments produced by splitting at
each element matching predicate. Matching elements are dropped.
Examples
let v = [1, -1, 2, 3, -1, 4].split(where: { it < 0 });
for seg in v { ... }public func starts[__opaque_0](with: __opaque_0) -> Bool where __opaque_0: Slice[T]
public func starts[__opaque_0](with: __opaque_0) -> Bool where __opaque_0: Slice[T]true if the leading elements match prefix. O(k) where k is
the prefix length. Accepts any Slice[T] conformer.
Examples
[1, 2, 3].starts(with: [1, 2]); // true
[1, 2, 3].starts(with: [2, 3]); // false
[1, 2, 3].starts(with: []); // true (vacuous)public func suffix(Int64) -> ArraySlice[T]
public func suffix(Int64) -> ArraySlice[T]Returns a slice over the last count elements. O(1).
Errors
Panics if count > self.count.
Examples
[1, 2, 3, 4, 5].suffix(2); // ArraySlice[4, 5]
public func unique() -> Array[T]
public func unique() -> Array[T]Returns a new array with duplicates removed, preserving first-occurrence order. O(n²).
For the mutating variant on Array, see removeDuplicates().
Examples
[1, 2, 1, 3, 2, 4].unique(); // [1, 2, 3, 4]
public func windows(of: Int64) -> WindowsView[T]
public func windows(of: Int64) -> WindowsView[T]Multi-pass lazy view over overlapping size-sized sliding
windows.
Adjacent windows overlap by size - 1 elements. Empty when the
source has fewer than size elements.
Errors
Panics if size <= 0.
Examples
let v = [1, 2, 3, 4].windows(of: 2);
v.count; // 3
for w in v { ... }Subscripts
public subscript[I](I) -> I.SeqOutput { get set }
public subscript[I](I) -> I.SeqOutput { get set }ImplementsIterable
Associated Types
type Item = T
type Item = TIterable element type — the element produced by iter().next().
type TargetIterator = ArraySliceIterator[T]
type TargetIterator = ArraySliceIterator[T]Iterable iterator type — the concrete iterator returned by iter().
Methods
public func iter() -> ArraySliceIterator[T]
public func iter() -> ArraySliceIterator[T]Returns a forward iterator over the array's elements.
ImplementsExpressibleByArrayLiteral
Initializers
init(arrayLiteral: LiteralSlice[Element])
init(arrayLiteral: LiteralSlice[Element])Builds an instance from a literal slice of elements.
Implements_ExpressibleByArrayLiteral
Associated Types
type Element = T
type Element = TPattern-matching element type — used by ArrayMatchable for
[a, b, ..rest] patterns.
type Element = T
type Element = TArrayMatchable element type — what the pattern bindings extract.
Initializers
init(_arrayLiteralPointer: consuming lang.ptr[Element], _arrayLiteralCount: consuming lang.i64)
init(_arrayLiteralPointer: consuming lang.ptr[Element], _arrayLiteralCount: consuming lang.i64)Compiler-emitted init taking a raw pointer and count.
Both params are consuming: the compiler hands ownership of the
stack buffer's address (and the count) over to the implementation,
which stores them in its own storage. This convention is what the
MIR lowering's structural predicate looks for — implementations
that deviate will be silently skipped during literal lowering.
ImplementsCloneable
Methods
public func clone() -> Array[T]
public func clone() -> Array[T]Returns an Array[T] sharing the same storage; the deep copy is
deferred until either side mutates.
O(1) — just bumps the storage CowBox's refcount. The first
mutation on either the original or the clone triggers
makeUnique(), which deep-copies the buffer so the two arrays
diverge.
Examples
let a = [1, 2, 3];
var b = a.clone(); // O(1), shares storage
b.append(4); // b deep-copies here; a is unchangedImplementsDefaultable
Initializers
init()
init()Builds the default-valued instance.
ImplementsEquatable
Associated Types
type Output = Bool
type Output = BoolMethods
public func equal(to: Self) -> Bool
public func equal(to: Self) -> BoolBridges Equal.equal(to:) to Equatable.isEqual(to:).
func isEqual(to: Self) -> Bool
func isEqual(to: Self) -> BoolReturns true iff self and other are considered equal. Should
be reflexive, symmetric, and transitive — Hashable requires equal
values to hash equal, so don't drift from those laws.
public func notEqual(to: Self) -> Bool
public func notEqual(to: Self) -> BoolDefault !=: delegates to == so there's a single source of truth.
ImplementsArrayMatchable
Associated Types
type Element
type ElementMethods
public func matchGet(Int64) -> T
public func matchGet(Int64) -> TPattern-matcher hook reading the element at index (no bounds
check).
Safety
The matcher only calls this with indices it has already validated
against matchLength(), so the unchecked read is safe in that
context.
public func matchLength() -> Int64
public func matchLength() -> Int64Pattern-matcher hook returning the array's count.
Used by the matcher to decide whether the scrutinee has enough elements for a fixed-arity pattern.
public func matchSlice(Int64, Int64) -> ArraySlice[T]
public func matchSlice(Int64, Int64) -> ArraySlice[T]Pattern-matcher hook returning the half-open [from, to) slice.
Used to bind ..rest segments. The matcher guarantees the
indices are in range.
Defined in lang/std/collections/array.ks