The “for-in” loop in Swift

The concept of a “for-in” loop in Swift is to be able to iterate over a sequence of values, such as an array, a range, a string or a dictionary, and perform a block of code for each of those items one at a time. The general syntax of a `for-in` loop in Swift is as follows:

for item in sequence {
    // code to run for each item

In this syntax, “item” is a variable that takes on the value of each element in the “sequence”, and the block of code inside the loop will be executed once for each “item” in the “sequence”.

Over an array

Here is an example of using a “for-in” loop to iterate over an array of numbers:

let numbers = [1, 2, 3, 4, 5]

for number in numbers {

/* Output

In this example, the “for-in” loop iterates over the array “numbers” and prints each number in the array to the console, one at a time.

The “for-in” loop is a very powerful construct in Swift, and it is used extensively in many different types of programming tasks such as iterating through user interface elements, parsing data, and manipulating collections.

Example: Sum of odd and even numbers

In this example an array of numbers is goven. The loop has the task of adding the individual numbers by category and giving the sum. Once the sum of the even numbers and once the sum of the odd numbers.

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

var odd = 0
var even = 0

for number in numberArray {
  if number % 2 == 1 {
    odd += number
  } else {
    even += number

print("The sum of all even numbers in this array is \(even)")
print("The sum of all odd numbers in this array is \(odd)")

/* Output
The sum of all even numbers in this array is 30
The sum of all odd numbers in this array is 25

Leave a Reply

Your email address will not be published. Required fields are marked *