Lesson 6 of 15

Loops

Loops

For-In Loops

Swift uses for x in range syntax. Ranges are created with ... (inclusive) or ..< (exclusive upper bound):

// 1 through 5 (inclusive)
for i in 1...5 {
    print(i)
}

// 0 through 4 (exclusive upper bound)
for i in 0..<5 {
    print(i)
}

While Loops

var n = 1
while n < 100 {
    n *= 2
}
print(n) // 128

Your Task

Write a function sumTo that takes an Int n and returns the sum of all integers from 1 to n (inclusive), using a for loop.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.