HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to SwiftVariablesData TypesOperatorsStringsArraysConditions (if / else)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ String
📚 Array & Dictionary
🔀 Condition & Loop
🧩 Function
Swift›Loops (for / while)

Loops (for / while)

for-in with ranges (1...5), iterating over arrays, and conditional repetition with while.

Simple enough for a 5-year-old to understand

range with for

1...5 is a closed range (includes 5). 1..<5 does not include 5.

Example code
1
for i in 1...3 {
1, 2, 3 (3 included).
Loop1, 2, 3 (3 included).
2
print(i)
3
}
Loop
💡 Hint: 1...5 → includes 5; 1..<5 → excludes 5.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Print the numbers from 1 to 5 vertically using a for loop.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

Loops are a way to do a task over and over again. In Swift, there are two main forms: the for-in loop iterates over the elements of a collection or a range, while the while loop repeats as long as a condition is true.

Swift's for-in loop is different from the counter-controlled loop in C: you don't manage the index yourself, the collection gives you the elements. This eliminates most out-of-bounds errors right from the start. Still, if you need the index, you can work with ranges or enumerated.

Range operators play a critical role here. The 0..<n format gives all indices of a collection with n elements; 0...n produces one extra and leads to an out-of-bounds error in the array. The difference between these two signs is the most common mistake made by beginners.

What you will learn

  • for-in loop and ranges
  • difference between while and repeat-while
  • Using break and continue
  • Iterating with step skipping
  • Iterating along with the index

Who is this for?

  • Beginners learning repetitive operations
  • Developers who will work with collections
  • Those getting bounds errors in loops

When to use?

If the number of elements is known or you are iterating over a collection, for-in is the right choice.

If the number of repetitions is not known in advance, for example, waiting until a condition is met, while is appropriate.

Common mistakes

Wrong

let items = ["a", "b", "c"]
for i in 0...items.count {
  print(items[i])
}

The three dots include the upper bound, meaning the loop produces the values 0,1,2,3 and stops on the last step with "Index out of range". Array indices always end at one less than the number of elements. Using the half-open range operator gives the correct range.

Correct

let items = ["a", "b", "c"]
for i in 0..<items.count {
  print(items[i])
}

Wrong

var i = 0
while i < 5 {
  print(i)
}

Since the counter never increments, the condition remains true forever and the program never ends. You have to ensure progress yourself in while loops; this is the best example of why the for-in loop is safer.

Correct

var i = 0
while i < 5 {
  print(i)
  i += 1
}

Wrong

for i in 5..<0 {
  print(i)
}

In Swift, the lower bound of a range cannot be greater than the upper bound; this code crashes with "Fatal error: Range requires lowerBound <= upperBound". To count backward, you need to reverse the range or use stride.

Correct

for i in (0..<5).reversed() {
  print(i)
}

Frequently asked questions

How do I access both the index and the element at the same time?

The enumerated() method gives the index and element pair at each step. This way, you can use both the sequence number and the value, while also avoiding the boundary risk of index access.

How to write a loop that increments by twos?

stride(from:to:by:) is used. The range operator does not allow specifying a step; stride allows you to progress with the step you want in both forward and backward directions.

When is repeat-while used?

When the body needs to run at least once. The while loop checks the condition at the beginning and might not run at all; repeat-while runs first, then checks. The scenario of asking until valid input is received from the user is a typical example.

Summary

for-in iterates over collections and ranges.

..< excludes the upper bound; this is the correct one for array indices.

You must ensure progress in a while loop.

A reverse range cannot be written directly, reversed or stride is used.

enumerated gives the index and the element together.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code