swift
  1. swift-loops

Swift Loops

Swift loops are used to execute a block of code repeatedly until a certain condition is met. There are three types of loops in Swift: for, while, and repeat-while. Each of these loops has its own syntax and use cases.

Syntax

For Loop

for index in start...finish {
    // Code to execute with index
}

While Loop

while condition {
    // Code to execute
}

Repeat-While Loop

repeat {
    // Code to execute
} while condition

Example

For Loop

for num in 1...5 {
    print(num)
}

While Loop

var num = 1
while num <= 5 {
    print(num)
    num += 1
}

Repeat-While Loop

var num = 1
repeat {
    print(num)
    num += 1
} while num <= 5

Output

For Loop

1
2
3
4
5

While Loop

1
2
3
4
5

Repeat-While Loop

1
2
3
4
5

Explanation

For Loop

A for loop is used when you know the number of iterations you need to perform. In the above example, num is initialized to 1 and the loop will execute until num is greater than 5. Each iteration will increment num by 1 and print its current value.

While Loop

A while loop is used when you do not know the number of iterations you need to perform. The loop will execute as long as the condition is true. In the above example, num is initialized to 1 and the loop will execute until num is greater than 5. Each iteration will print the current value of num and increment it by 1.

Repeat-While Loop

A repeat-while loop is similar to a while loop, but it guarantees that the code block will be executed at least once, even if the condition is false. The loop will execute until the condition is false. In the above example, num is initialized to 1 and the loop will execute until num is greater than 5. Each iteration will print the current value of num and increment it by 1.

Use

Swift loops are used to perform repetitive tasks in code. They can be used to iterate over arrays, perform calculations, or perform any other task that requires repeated execution.

Important Points

  • Swift has three types of loops: for, while, and repeat-while
  • A for loop is used when you know the number of iterations you need to perform
  • A while loop is used when you do not know the number of iterations you need to perform
  • A repeat-while loop guarantees that the code block will be executed at least once, even if the condition is false
  • Loops are commonly used to iterate over arrays or perform calculations

Summary

Swift loops are essential for performing repetitive tasks in code. They provide a way to iterate over arrays, perform calculations, and perform any other tasks that require repeated execution. Swift provides three types of loops: for, while, and repeat-while, each with its own syntax and use cases.

Published on: