for / in
for iterates over the elements of a collection or the values of a range, binding each in turn to the loop variable.
for item in collection {
Print(item);
}
Iterating a Collection
A for loop walks an array or slice element by element, in order. The loop variable holds each element directly — no index bookkeeping is required:
let nums = [1, 2, 3, 4, 5];
var sum = 0;
for n in nums {
sum += n;
}
Iterating a Range
A range generates a sequence of integers. 0..10 is half-open — the end is excluded — while 0..=10 includes the end:
for i in 0..10 {
Print(i); // prints 0 through 9
}
for i in 0..=10 {
Print(i); // prints 0 through 10 (inclusive)
}
Ranges are the idiomatic way to repeat something a fixed number of times or to walk a collection by index when you need the position.
Exiting Early
break leaves the loop immediately; continue skips to the next element or value.
See Also
while— looping on a condition rather than a sequence- Ranges — the interval values
foriterates over - Arrays and Slices — the collections
foriterates over break/continue— altering loop control flow
while
while repeats its body as long as the condition holds. The condition is tested before each iteration, so the body may run zero times.
loop
loop creates an unconditional infinite loop. It runs until a break exits it. Prefer loop over while true — it states the intent directly and cannot be mistaken for a condition that might change.