← Swift tutorial

Swift

Loops

Swift's for-in loop steps through a range or collection directly.

Example: two ranges, one small but important difference

var total = 0
for i in 1...5 {
    total += i
}
print("Total: \(total)")
Total: 15

1...5 (three dots) includes both endpoints, 1 through 5. 1..<5 (two dots and a less-than) excludes the last one, covering 1 through 4 only, a genuinely easy pair to mix up, and worth double-checking whenever an off-by-one result shows up unexpectedly in your own code.

Example
var total = 0
for i in 1...5 {
    total += i
}
print("Total: \(total)")
Output
Total: 15
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account