3.1 For Loops

Loops for in

  • specify a local variable name and the collection/string to be iterated over
  • must be over a range of values in increasing order
  • swift figures out how to use loops with strings
  • loop constants are only visible within the scope of the loop
  • can use wildcard _ for the inferred constant if you are just looping
// basic -> prints #'s<br>
for i in 1...10 {<br>
  print("i = \(i)")<br>
}<br>
<br>
// no counter access, just loops -> Hello 5x<br>
for _ in 1...5 {<br>
  print("Hello")<br>
}<br>
<br>
// -> populates an array with 1-50<br>
var cellContent = [Int]()<br>
for i in 1...50 {<br>
  cellContent.append(i)<br>
}<br>
<br>
// -> prints each name<br>
let names = ["Jim", "John", "Jill"]<br>
for n in names {<br>
  print(n)<br>
}<br>
<br>
// -> prints S w i f t<br>
for i: Character in "Swift" {<br>
  print(i)<br>
}
  • no need to initialize i (or any other given name) → it is type inferred

Loop for case in where

  • ​iterate the loop over a range and execute code when a condition is met
// -> 3 6 9 12...<br>
for case let i in 1...50 where i % 3 == 0 {<br>
  print(i)<br>
}

Loop for in stride

  • looping function that allows any increments / decrements
  • allows a half-open range where termination doesn’t finish exactly on the through value
// -> 11 9 7...<br>
for count in stride(from: 11, to: 1, by: -2) {<br>
  print("\(count)")<br>
}

Loop for in reversed

// -> 5 4 3...<br>
for reversedCount in (1...5).reversed() {<br>
  print("\(reversedCount)")<br>
}