create a loop in swift

Swift offers several types of loops that can be used to execute a block of code repeatedly.

  1. The for-in loop is used to iterate over a collection, such as an array or a range of numbers:
main.swift
for item in myArray {
  // code to execute for each item in the array
}
72 chars
4 lines
  1. The while loop is used to execute a block of code repeatedly as long as a condition is true:
main.swift
while condition == true {
  // code to execute while the condition is true
}
77 chars
4 lines
  1. The repeat-while loop is similar to the while loop, but the code inside the loop is always executed at least once:
main.swift
repeat {
  // code to execute at least once
} while condition == true
70 chars
4 lines

Here's an example of using a for-in loop to iterate over an array of numbers and print each one:

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

for number in numbers {
  print(number)
}
73 chars
6 lines

gistlibby LogSnag