MutRefSliceIterator
public struct MutRefSliceIterator[T] { /* private fields */ }Forward iterator yielding MUTABLE REFERENCES (&mutating T) to
contiguous elements — in-place mutation without writeback
(for x in arr.mutableRefs() { x += 1 }). Surfaced as
Array.mutableRefs(), which runs the COW barrier before handing out
the buffer.
Invalidation
Same contract as RefSliceIterator: mutating the source collection's
STRUCTURE while iterating invalidates the cursor and any yielded
reference. Element writes through the yielded references are the
intended use.
Representation
A Pointer[T] cursor and an Int64 countdown.
Initializers
public init(ptr: Pointer[T], remaining: Int64)
public init(ptr: Pointer[T], remaining: Int64)Builds an iterator from a starting pointer and remaining count.
ImplementsIterator
Associated Types
type Item = &mutating T
type Item = &mutating Ttype TargetIterator = Self
type TargetIterator = SelfMethods
public mutating func all(where: (Item) -> Bool) -> Bool
public mutating func all(where: (Item) -> Bool) -> BoolTrue if every element satisfies predicate. Stops at the first
failure. True for an empty iterator (vacuous truth).
Examples
[2, 4, 6].iter().all { it % 2 == 0 }; // true
[2, 3, 4].iter().all { it % 2 == 0 }; // false (stops at 3)
[].iter().all { false }; // true (empty)public mutating func any(where: (Item) -> Bool) -> Bool
public mutating func any(where: (Item) -> Bool) -> BoolTrue if any element satisfies predicate. Stops at the first
match. False for an empty iterator.
Examples
[1, 2, 3, 4].iter().any { it > 3 }; // true (stops at 4)
[1, 2, 3].iter().any { it > 10 }; // false
[].iter().any { true }; // falsepublic func chain[Other](Other) -> ChainIterator[Self, Other] where Other: Iterator, Other.Item == Item
public func chain[Other](Other) -> ChainIterator[Self, Other] where Other: Iterator, Other.Item == ItemYields all of self, then all of other. Both must produce the
same Item type.
Examples
[1, 2].iter().chain([3, 4].iter()).collect(); // [1, 2, 3, 4]
public consuming func collect() -> Array[Item]
public consuming func collect() -> Array[Item]Drains the iterator into an Array[Item]. Eager and O(n). Use
at the end of an adapter chain to materialise the result.
Examples
[1, 2, 3].iter().filter { it > 1 }.collect(); // [2, 3]
(1..5).iter().map { it * it }.collect(); // [1, 4, 9, 16]public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T]
public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T]Drops Nones and unwraps Somes — the identity-transform special
case of filterMap. Available when the iterator already yields
optionals.
Examples
let xs: [Int64?] = [.Some(1), .None, .Some(2), .None, .Some(3)];
xs.iter().compactMap().collect(); // [1, 2, 3]public mutating func contains(Item) -> Bool
public mutating func contains(Item) -> BoolTrue if any element equals element. Short-circuits.
Examples
[1, 2, 3].iter().contains(2); // true
[1, 2, 3].iter().contains(5); // falsepublic consuming func count() -> Int64
public consuming func count() -> Int64Counts the elements by walking the whole iterator. O(n) — for
types that already know their length, prefer
ExactSizeIterator.remaining.
Examples
[1, 2, 3, 4, 5].iter().filter { it % 2 == 0 }.count(); // 2
public func cycle() -> CycleIterator[Self]
public func cycle() -> CycleIterator[Self]Restarts iteration from the beginning whenever the inner iterator
is exhausted, producing an infinite sequence. Always combine with
take (or another short-circuiting consumer) — otherwise the
result is unbounded.
Examples
[1, 2, 3].iter().cycle().take(7).collect();
// [1, 2, 3, 1, 2, 3, 1]public func enumerate() -> EnumerateIterator[Self]
public func enumerate() -> EnumerateIterator[Self]Pairs each element with its zero-based position.
Examples
for (i, item) in arr.iter().enumerate() {
print("Index \{i}: \{item}")
};public func filter(where: consuming (Item) -> Bool) -> FilterIterator[Self]
public func filter(where: consuming (Item) -> Bool) -> FilterIterator[Self]Yields only elements where predicate returns true. Lazy —
elements are tested as they're pulled.
Examples
[1, 2, 3, 4, 5].iter().filter { it % 2 == 0 }.collect(); // [2, 4]
public func filterMap[U](as: consuming (Item) -> U?) -> FilterMapIterator[Self, U]
public func filterMap[U](as: consuming (Item) -> U?) -> FilterMapIterator[Self, U]Combined map + filter — transform returns Optional[U]; None
values are skipped. Use over map(...).filter(...) when the
transform itself decides whether the element belongs.
Examples
["1", "two", "3"].iter()
.filterMap { Int64.parse(it) }
.collect(); // [1, 3]public mutating func first(where: (Item) -> Bool) -> Item?
public mutating func first(where: (Item) -> Bool) -> Item?First element matching predicate, or None. Stops at the first
match.
Examples
[1, 2, 3, 4, 5].iter().first { it > 3 }; // Some(4)
[1, 2, 3].iter().first { it > 10 }; // Nonepublic mutating func firstIndex(where: (Item) -> Bool) -> Int64?
public mutating func firstIndex(where: (Item) -> Bool) -> Int64?Index of the first element matching predicate, or None.
Examples
["a", "b", "c"].iter().firstIndex(where: { it == "b" }); // Some(1)
[1, 2, 3].iter().firstIndex(where: { it > 10 }); // Nonepublic func flatMap[U](as: consuming (Item) -> U) -> FlatMapIterator[Self, U] where U: Iterator
public func flatMap[U](as: consuming (Item) -> U) -> FlatMapIterator[Self, U] where U: IteratorMaps each element to an iterator and concatenates the results. The monadic bind for iterators.
Examples
[[1, 2], [3, 4], [5]].iter()
.flatMap { it.iter() }
.collect(); // [1, 2, 3, 4, 5]
// Conditional expand — drop odd, double even
[1, 2, 3].iter()
.flatMap { if it % 2 == 0 { [it, it].iter() } else { [].iter() } }
.collect(); // [2, 2]public func flatten() -> FlattenIterator[Self]
public func flatten() -> FlattenIterator[Self]Concatenates the inner iterators into one flat stream. Each inner
iterator is fully drained before moving to the next. The
already-have-iterators counterpart of flatMap.
Examples
let nested = [[1, 2], [3, 4], [5]].iter().map { it.iter() };
nested.flatten().collect(); // [1, 2, 3, 4, 5]public consuming func fold[Acc](from: Acc, by: (Acc, Item) -> Acc) -> Acc
public consuming func fold[Acc](from: Acc, by: (Acc, Item) -> Acc) -> AccLeft fold — start at initial and walk left to right, applying
combine(acc, element). Returns initial for an empty iterator.
Examples
[1, 2, 3, 4].iter().fold(from: 0) { (acc, x) in acc + x }; // 10
[1, 2, 3].iter().fold(from: 1) { (acc, x) in acc * x }; // 6
[].iter().fold(from: 42) { (acc, x) in acc + x }; // 42public consuming func forEach((Item) -> ())
public consuming func forEach((Item) -> ())Calls action on every element, discarding return values. Use
tryForEach if you need to short-circuit on failure.
Examples
[1, 2, 3].iter().forEach { print(it) };
public func fuse() -> FusedIterator[Self]
public func fuse() -> FusedIterator[Self]Locks None once seen — protects against iterators that aren't
fused (i.e. that may produce more elements after returning None
once). After the first None, this adapter returns None
forever.
public func inspect(consuming (Item) -> ()) -> InspectIterator[Self]
public func inspect(consuming (Item) -> ()) -> InspectIterator[Self]Calls inspector on each element as it flows through, leaving
the value otherwise untouched. Useful for logging or
instrumenting an adapter chain mid-pipeline.
Examples
[1, 2, 3].iter()
.inspect { print("before filter: \{it}") }
.filter { it > 1 }
.inspect { print("after filter: \{it}") }
.collect();public func intersperse(with: Item) -> IntersperseIterator[Self]
public func intersperse(with: Item) -> IntersperseIterator[Self]Inserts separator between consecutive elements. Empty inputs
stay empty; single-element inputs get no separator.
Examples
[1, 2, 3].iter().intersperse(with: 0).collect();
// [1, 0, 2, 0, 3]public func intersperseWith(with: consuming () -> Item) -> IntersperseWithIterator[Self]
public func intersperseWith(with: consuming () -> Item) -> IntersperseWithIterator[Self]Like intersperse, but builds each separator on demand by calling
separator(). Use when the separator is expensive or needs to
vary by call.
Examples
var counter = 0;
[1, 2, 3].iter()
.intersperseWith { counter += 1; counter * 10 }
.collect(); // [1, 10, 2, 20, 3]public consuming func isSorted() -> Bool
public consuming func isSorted() -> BoolTrue if elements come out in ascending order. True for empty or single-element iterators (vacuous). Short-circuits on the first out-of-order pair.
Examples
[1, 2, 3, 4, 5].iter().isSorted(); // true
[1, 3, 2, 4, 5].iter().isSorted(); // false
[1, 1, 2, 2, 3].iter().isSorted(); // true (equal allowed)public consuming func isSortedDescending() -> Bool
public consuming func isSortedDescending() -> BoolTrue if elements come out in descending order. Mirror of
isSorted.
func iter() -> Self
func iter() -> SelfReturns self. The blanket conformance pivot — iterators are
iterables.
public consuming func last() -> Item?
public consuming func last() -> Item?Last element, or None if empty. Consumes the entire iterator —
O(n) even for sequences whose last element is cheap to address
directly.
public func map[U](as: consuming (Item) -> U) -> MapIterator[Self, U]
public func map[U](as: consuming (Item) -> U) -> MapIterator[Self, U]Applies transform to each element. Lazy — the function only
fires when the downstream pulls a value.
Examples
[1, 2, 3].iter().map { it * 2 }.collect(); // [2, 4, 6]
["hi", "yo"].iter().map { it.count }.collect(); // [2, 2]public consuming func max() -> Item?
public consuming func max() -> Item?Largest element, or None for an empty iterator. Ties go to the
first occurrence.
public consuming func min() -> Item?
public consuming func min() -> Item?Smallest element, or None for an empty iterator. Ties go to the
first occurrence.
Examples
[3, 1, 4, 1, 5].iter().min(); // Some(1)
[].iter().min(); // Nonepublic mutating func next() -> Optional[&mutating T]
public mutating func next() -> Optional[&mutating T]Yields a mutable reference to the next element in place, or
.None when the count reaches zero.
public mutating func nth(Int64) -> Item?
public mutating func nth(Int64) -> Item?Returns the element at index n (zero-based), consuming
everything up to and including it. None if n is past the end.
Examples
[10, 20, 30, 40].iter().nth(2); // Some(30)
[10, 20].iter().nth(5); // None
[10, 20, 30].iter().nth(0); // Some(10)public func peekable() -> PeekableIterator[Self]
public func peekable() -> PeekableIterator[Self]Wraps self so you can look at the next element without
consuming it.
Examples
var it = [1, 2, 3].iter().peekable();
it.peek(); // Some(1) — no consumption
it.peek(); // Some(1) — still
it.next(); // Some(1) — now consumed
it.peek(); // Some(2)public consuming func product() -> Item
public consuming func product() -> ItemProduct of every element. Returns Item.one for an empty
iterator.
Examples
[1, 2, 3, 4, 5].iter().product(); // 120
(1..=5).iter().product(); // 120 (5!)
[].iter().product(); // 1public consuming func reduce(by: (Item, Item) -> Item) -> Item?
public consuming func reduce(by: (Item, Item) -> Item) -> Item?Like fold, but seeds the accumulator with the first element
instead of taking an explicit initial. Returns None for an
empty iterator.
Examples
[1, 2, 3, 4].iter().reduce { (a, b) in a + b }; // Some(10)
[5].iter().reduce { (a, b) in a + b }; // Some(5)
[].iter().reduce { (a, b) in a + b }; // Nonepublic func scan[Acc](from: Acc, by: consuming (Acc, Item) -> Acc) -> ScanIterator[Self, Acc]
public func scan[Acc](from: Acc, by: consuming (Acc, Item) -> Acc) -> ScanIterator[Self, Acc]Like fold, but yields each intermediate accumulator value
instead of just the final one. Useful for prefix sums, running
products, and any "carry state along" pattern.
Examples
// Running sum
[1, 2, 3, 4].iter()
.scan(from: 0) { (acc, x) in acc + x }
.collect(); // [1, 3, 6, 10]public func skip(Int64) -> SkipIterator[Self]
public func skip(Int64) -> SkipIterator[Self]Drops the first count elements, then yields the rest.
Examples
[1, 2, 3, 4, 5].iter().skip(2).collect(); // [3, 4, 5]
[1, 2].iter().skip(10).collect(); // []public func skipWhile(where: consuming (Item) -> Bool) -> SkipWhileIterator[Self]
public func skipWhile(where: consuming (Item) -> Bool) -> SkipWhileIterator[Self]Drops elements while predicate is true, then yields every
remaining element (including ones that would also satisfy the
predicate). Mirror of takeWhile.
Examples
[1, 2, 3, 4, 1, 2].iter()
.skipWhile { it < 3 }
.collect(); // [3, 4, 1, 2]public consuming func sorted() -> Array[Item]
public consuming func sorted() -> Array[Item]Collects into an Array[Item], sorted ascending. Eager and
O(n log n) — calls Array.sort(by:) after collect().
Examples
[3, 1, 4, 1, 5].iter().sorted(); // [1, 1, 3, 4, 5]
[3, 1, 2].iter().filter { it > 1 }.sorted(); // [2, 3]public func stepBy(Int64) -> StepByIterator[Self]
public func stepBy(Int64) -> StepByIterator[Self]Yields every n-th element, starting at the first. n == 0 is
undefined (the adapter will spin forever).
Examples
[0, 1, 2, 3, 4, 5, 6].iter().stepBy(2).collect(); // [0, 2, 4, 6]
public consuming func sum() -> Item
public consuming func sum() -> ItemSum of every element. Returns Item.zero for an empty iterator.
Examples
[1, 2, 3, 4, 5].iter().sum(); // 15
[1.5, 2.5, 3.0].iter().sum(); // 7.0
[].iter().sum(); // 0public func take(Int64) -> TakeIterator[Self]
public func take(Int64) -> TakeIterator[Self]Yields at most the first count elements; stops early even if
more are available.
Examples
[1, 2, 3, 4, 5].iter().take(3).collect(); // [1, 2, 3]
[1, 2].iter().take(10).collect(); // [1, 2]public func takeWhile(where: consuming (Item) -> Bool) -> TakeWhileIterator[Self]
public func takeWhile(where: consuming (Item) -> Bool) -> TakeWhileIterator[Self]Yields elements until predicate first returns false, then
stops. The "first failing" element is not yielded.
Examples
[1, 2, 3, 4, 1, 2].iter()
.takeWhile { it < 4 }
.collect(); // [1, 2, 3]public mutating func tryFold[Acc, E](from: Acc, by: (Acc, Item) -> Result[Acc, E]) -> Result[Acc, E]
public mutating func tryFold[Acc, E](from: Acc, by: (Acc, Item) -> Result[Acc, E]) -> Result[Acc, E]Fold with early exit on Err. The combine returns Result; the
first Err halts iteration and is returned. If everything
succeeds, returns Ok(final accumulator).
Examples
// Stop the moment a parse fails
["1", "2", "3"].iter()
.tryFold(from: 0) { (acc, s) in
match Int64.parse(s) {
.Some(n) => .Ok(acc + n),
.None => .Err("parse error")
}
}; // Ok(6)
["1", "bad", "3"].iter()
.tryFold(from: 0) { (acc, s) in
match Int64.parse(s) {
.Some(n) => .Ok(acc + n),
.None => .Err("parse error")
}
}; // Err("parse error")public mutating func tryForEach[E](consuming (Item) -> Result[(), E]) -> Result[(), E]
public mutating func tryForEach[E](consuming (Item) -> Result[(), E]) -> Result[(), E]forEach with early exit on Err. Mirror of tryFold for the
"do something with each element" shape.
Examples
files.iter().tryForEach { (path) in
File.delete(path) // Result[(), IoError]
}; // stops on first failurepublic consuming func unzip[A, B]() -> (Array[A], Array[B]) where Item == (A, B)
public consuming func unzip[A, B]() -> (Array[A], Array[B]) where Item == (A, B)Splits an iterator of pairs into two parallel arrays. Inverse of
zip.
Examples
let pairs = [(1, "a"), (2, "b"), (3, "c")];
let (nums, strs) = pairs.iter().unzip();
// nums = [1, 2, 3], strs = ["a", "b", "c"]public func zip[Other](Other) -> ZipIterator[Self, Other] where Other: Iterator
public func zip[Other](Other) -> ZipIterator[Self, Other] where Other: IteratorPairs elements from self and other. Stops as soon as either
side runs out.
Examples
let names = ["Alice", "Bob", "Charlie"];
let ages = [30, 25, 35];
names.iter().zip(ages.iter()).collect();
// [("Alice", 30), ("Bob", 25), ("Charlie", 35)]Defined in lang/std/memory/pointer.ks