Swift For Loop

A Swift for-in loop runs a block of code once for each value in a sequence. You can use it with arrays, ranges, strings, dictionaries, sets, and other types that conform to Swift’s Sequence protocol.

This tutorial explains Swift for-loop syntax and shows how to loop through arrays, characters, numeric ranges, indexes, key-value pairs, and values that advance by a custom step.

Swift For-In Loop Syntax

Following is syntax of Swift For Loop in a program.

</>
Copy
 for index in var {
    // set of statements
 }

var could be a collection such as range of numbers, characters in a string or items in an array.

index is the element in var.

In modern Swift terminology, the value after in is a sequence, and the name before in is the loop variable. The loop variable receives one element during each iteration.

</>
Copy
for element in sequence {
    // Statements executed for each element
}

Swift For Loop Over an Array

In this example, we will use for loop to iterate over an array of numbers.

main.swift

</>
Copy
var salaries:[Int] = [500, 620, 410, 586]

for salary in salaries {
   print( "Salary paid to employee: \(salary)")
}

Output

$swift for_loop_example.swift
Salary paid to employee: 500
Salary paid to employee: 620
Salary paid to employee: 410
Salary paid to employee: 586

The loop preserves the array’s iteration order. The constant salary receives one array element at a time, and its scope is limited to the loop body.

Swift For Loop Through Characters in a String

In this example, we will use for loop to iterate for each character in a string.

main.swift

</>
Copy
var salaries:[Int] = [500, 620, 410, 586]

for salary in salaries {
   print( "Salary paid to employee: \(salary)")
}

Output

$swift for_loop_example.swift
character: t
character: u
character: t
character: o
character: r
character: i
character: a
character: l
character: k
character: a
character: r
character: t

The intended string iteration that matches the output is shown below. Swift strings are collections of Character values, so a for-in loop can visit each character directly.

</>
Copy
let text = "tutorialkart"

for character in text {
    print("character: \(character)")
}

Swift For Loop Over a Half-Open Range

In this example, we will use For Loop to iterate over a range of numbers.

main.swift

</>
Copy
var range = 8..<12

for item in range {
   print( "item: \(item)")
}

Output

$swift for_loop_example.swift
item: 8
item: 9
item: 10
item: 11

The half-open range operator ..< includes its lower bound and excludes its upper bound. Therefore, 8..<12 produces 8, 9, 10, and 11.

Swift For Loop from 1 to 10

Use the closed range operator ... when both endpoints must be included. The following loop prints the numbers from 1 through 10.

</>
Copy
for number in 1...10 {
    print(number)
}

Output

1
2
3
4
5
6
7
8
9
10

Use 1..<10 instead when the upper bound must be excluded; that range stops at 9.

Swift For Loop with an Array Index

When you need both the position and the value, call enumerated(). It returns pairs containing a zero-based offset and the corresponding element.

</>
Copy
let cities = ["Delhi", "Mumbai", "Chennai"]

for (index, city) in cities.enumerated() {
    print("\(index): \(city)")
}

Output

0: Delhi
1: Mumbai
2: Chennai

The number returned by enumerated() is an integer offset. For an Array, it corresponds to the usual zero-based index. For a general collection, do not assume that the offset is the collection’s native Index type.

Swift For Loop with a Custom Step Using stride()

Swift does not use the C-style for loop syntax for incrementing a counter. Use stride(from:to:by:) or stride(from:through:by:) when values must increase or decrease by a custom amount.

</>
Copy
for number in stride(from: 0, through: 10, by: 2) {
    print(number)
}

Output

0
2
4
6
8
10

through: includes the final value when the stride reaches it. The to: form excludes the final boundary. A negative by: value creates a descending sequence.

</>
Copy
for number in stride(from: 10, through: 2, by: -2) {
    print(number)
}

Swift For Loop Over Dictionary Key-Value Pairs

A dictionary iteration produces a tuple containing a key and its associated value. Dictionary order should not be used as a stable presentation order unless the keys are sorted explicitly.

</>
Copy
let scores = [
    "Asha": 92,
    "Ravi": 86
]

for (name, score) in scores {
    print("\(name): \(score)")
}

To produce a predictable key order, iterate over scores.keys.sorted() and retrieve each value by key.

Swift For Loop with a where Condition

Add a where clause when only elements that satisfy a condition should execute the loop body.

</>
Copy
let numbers = [1, 2, 3, 4, 5, 6]

for number in numbers where number.isMultiple(of: 2) {
    print(number)
}

Output

2
4
6

A where clause filters iterations before entering the body. It can be clearer than placing a simple if statement inside the loop.

Skipping or Stopping Swift For-Loop Iterations

Use continue to skip the remaining statements in the current iteration. Use break to stop the loop completely.

</>
Copy
for number in 1...8 {
    if number == 3 {
        continue
    }

    if number == 7 {
        break
    }

    print(number)
}

Output

1
2
4
5
6

Ignoring the Swift For-Loop Variable

Use an underscore when the current sequence value is not needed and only the number of repetitions matters.

</>
Copy
for _ in 1...3 {
    print("Retrying")
}

Modifying an Array During a Swift For Loop

Avoid changing the structure of the same array while iterating over it unless the behavior is deliberate and well understood. Removing or inserting elements can invalidate assumptions about indexes and may cause elements to be skipped.

For value transformations, prefer methods such as map. For removals based on a condition, prefer removeAll(where:). When index-based mutation is required and the array count stays unchanged, iterate over array.indices.

</>
Copy
var values = [2, 4, 6]

for index in values.indices {
    values[index] *= 2
}

print(values)

Output

[4, 8, 12]

Swift For-In Loop and SwiftUI ForEach Are Different

A Swift for-in loop is a language control-flow statement. SwiftUI’s ForEach is a view that creates repeated child views from identifiable data. A regular for-in loop cannot be inserted directly wherever a SwiftUI ViewBuilder expects views; use ForEach for that purpose.

Common Swift For-Loop Mistakes

  • Using the wrong range operator: 1...5 includes 5, while 1..<5 stops at 4.
  • Assuming dictionary order: Sort keys when a predictable order is required.
  • Treating an enumerated offset as every collection’s native index: Use the collection’s own index APIs when working with non-array collections.
  • Changing a collection’s size during iteration: Prefer dedicated transformation or removal methods.
  • Using a for loop when a while loop expresses the condition better: Choose while when repetition depends on a changing Boolean condition rather than a sequence.

Swift For Loop Frequently Asked Questions

How do I write a Swift for loop from 1 to 10?

Use for number in 1...10. The closed range operator includes both 1 and 10.

How do I get the index in a Swift for loop?

For an array, use for (index, value) in array.enumerated() when you need a zero-based offset and each value. Use array.indices when you need valid array indexes for mutation.

How do I increment a Swift for loop by 2?

Use stride(from:through:by:), such as stride(from: 0, through: 10, by: 2). Use the to: form when the final boundary must be excluded.

Can a Swift for loop iterate over a string?

Yes. A Swift string can be iterated as a sequence of Character values with for character in text.

When should I use a Swift while loop instead of a for loop?

Use for-in when iterating over a known sequence. Use while when repetition should continue only while a Boolean condition remains true and the number of iterations is not naturally represented by a sequence.

Swift For-Loop Editorial QA Checklist

  • Verify that closed and half-open range examples include the intended boundary values.
  • Confirm that each output block matches the corresponding Swift loop and input data.
  • Check that enumerated() is described as producing offsets rather than universal collection indexes.
  • Ensure stride examples use a step direction that can reach the stated boundary.
  • Review collection-mutation examples to make sure indexes remain valid throughout iteration.

Summary of Swift For-In Loops

A Swift for-in loop processes each value in a sequence. Use ranges for counted loops, enumerated() for array offsets, stride for custom increments, tuple destructuring for dictionaries, and where to filter iterations. In this Swift Tutorial, we have learned about Swift For Loop with syntax and examples for different types of collections.