In this tutorial, we will learn about different types of loops in Swift. We will cover the basics of `for-in`, `while`, and `repeat-while` loops.
A loop is a control flow statement that allows code to be executed repeatedly based on a condition.
Swift supports three types of loops: `for-in` loops, `while` loops, and `repeat-while` loops.
A `for-in` loop is used when iterating over a sequence, such as arrays, ranges, or strings. The syntax for the for-in loop is:
for item in sequence {
// Code block to be executed
}
A `while` loop is used when the number of iterations is not known beforehand. The syntax for the while loop is:
while condition {
// Code block to be executed
}
A `repeat-while` loop is similar to a `do-while` loop in other languages, where the code block is executed at least once before checking the condition. The syntax for the repeat-while loop is:
repeat {
// Code block to be executed
} while condition
for i in 1...5 {
print(i, terminator: " ")
}
1 2 3 4 5
i
and initialize it to 1.var i = 1
while i <= 3 {
print(i, terminator: " ")
i += 1
}
1 2 3
i
and initialize it to 1.var i = 1
repeat {
print(i, terminator: " ")
i += 1
} while i <= 3
1 2 3