create loop in swift

Looping is a fundamental concept in programming. In Swift, there are three types of loops: for-in loop, while loop, and repeat-while loop.

for-in loop

The for-in loop is used to iterate over a sequence such as an array, a range of numbers, or a string.

main.swift
let arrayOfNums = [1, 2, 3, 4, 5]

for num in arrayOfNums {
    print(num)
}

// Output: 1 2 3 4 5
99 chars
8 lines

while loop

The while loop is used when you want to keep looping until a certain condition is met.

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

// Output: 0 1 2 3 4
68 chars
8 lines

repeat-while loop

The repeat-while loop is similar to the while loop, but the code block is executed at least once before the condition is checked.

main.swift
var i = 0
repeat {
    print(i)
    i+=1
} while i<5

// Output: 0 1 2 3 4
75 chars
8 lines

In all three types of loops, you can use the break statement to exit the loop prematurely and the continue statement to skip the current iteration and continue with the next iteration.

gistlibby LogSnag