Ad space (banner)
๐ŸฆSwift Lessons
Lesson 5 / 68

Loops (for-in statements)

In this lesson you will learn to repeat work with a for-in statement in Swift so you can process ranges and collections efficiently. This is for anyone searching for "Swift for-in loop how to use".

A range such as 1...5 drives the repetition. You can also iterate an array or collection directly with for-in, handling the elements without worrying about indexes.

The sample code prints numbered messages from 1 to 5 with the range for i in 1...5. There is also the 1..<5 form, which excludes the upper bound, and you pick to suit the job.

A common stumbling block for beginners is the difference between ... and ..<. The first includes the upper bound and the second does not, and missing that fine distinction shifts the number of repetitions.

In real-world development, the for-in statement is one of the most frequently used constructs, above all for processing the contents of an array one item at a time.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)