Skip to content

for..in Loop

for..in is Vertex’s iteration statement. It walks a List<T>, binding each element to a pattern.

for n in [1, 2, 3] {
debug n
}

There is no while statement. Iteration is expressed with for..in, recursion, or collection combinators (map, filter, fold).

let names = ["Alice", "Bob", "Carol"]
for name in names {
debug "hello, ${name}"
}

The loop variable is immutable inside the body. To accumulate a result across iterations, declare a mutable let outside the loop, or prefer fold:

// Imperative style
mutable let total = 0
for n in [1, 2, 3] {
total = total + n
}
debug total // 6
// Functional style, no mutation
let total = [1, 2, 3].fold(0, fn(acc: Int, n: Int): Int { acc + n })
debug total // 6

The loop head accepts any pattern, so you can destructure tuples, records, or variants without an intermediate binding:

// Tuple destructuring
for #(index, value) in pairs {
debug "${index}: ${value}"
}
// Variant destructuring (matches only shapes of this variant)
for Circle(radius: r) in shapes {
debug "radius ${r}"
}
// Wildcard
for _ in items {
counter = counter + 1
}

List.enumerate() pairs each element with its zero-based index, returning a List<#(Int, T)> you can destructure:

for #(i, name) in names.enumerate() {
debug "${i}. ${name}"
}

Iteration order over a Map or Set is not guaranteed. Convert the collection to a list first to make the order explicit:

for #(k, v) in entries.toList() { ... } // Map.toList(): List<#(K, V)>
for item in set.toList() { ... } // Set.toList(): List<T>

This keeps the iteration order visible in the code rather than depending on hash-order surprises.

for..in emits as a Java-style for (T name : collection) { ... } in the generated Apex, with pattern destructuring expanded into the loop body.