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
for i in 1...10 {
  print("i = \(i)")
}

// no counter access, just loops -> Hello 5x
for _ in 1...5 {
  print("Hello")
}

// -> populates an array with 1-50
var cellContent = [Int]()
for i in 1...50 {
  cellContent.append(i)
}

// -> prints each name
let names = ["Jim", "John", "Jill"]
for n in names {
  print(n)
}

// -> prints S w i f t
for i: Character in "Swift" {
  print(i)
}
  • 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...
for case let i in 1...50 where i % 3 == 0 {
  print(i)
}

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...
for count in stride(from: 11, to: 1, by: -2) {
  print("\(count)")
}

Loop for in reversed

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