3.5 Control Transfer

continue

  • stops code execution and returns to the beginning of the loop’s start
// -> 1, 2, 3, 8, 9, 10
for i in 1...10 {
  if (i >= 4 && i <= 7) {
    continue
  }
  print(i)
}

example: Remove Vowels

// -> grtmndsthnklk
let puzzleInput = "great minds think alike"
var puzzleOutput = ""

for char in puzzleInput {
  switch char {
  case "a", "e", "i", "o", "u", " ":
    continue
  default:
    puzzleOutput.append(char)
  }
}
print(puzzleOutput)

break

  • completely interrupts the loop execution or switch
  • jumps to the end of the } brace
// -> 1, 2, 3
for i in 1...10 {
  if (i >= 4) && (i <= 7) {
    break
  }
  print(i)
}
switch puzzleOutput {
default:
  break
}
  • when used with a default switch, it says no action needs to be performed

fallthrough

  • auto evaluates the next case as true even if it isn’t
// -> number above
var numb = 6

switch numb {
case 0...6:
  print("number")
  fallthrough
default:													
  print("number above")
}

return

  • ends function execution and returns a specified value (or no value if used alone)
  • can have multiple return stmts (ie. a switch), but once one is executed, the function is exited
  • can return tuples

Labeled Statements

  • possible to label any control stmts (loops, if, switch)
  • then use break continue to navigate
// -> x = 1-5, y = 1
outerLoop: for x in 1...5 {
  innerLoop: for y in 1...3 {
    if y == 2 {
      continue outerLoop
    }
    print("x = \(x), y = \(y)")
  }
}