Flow Control: The art of conditional branching


if true { doSomething() } else { doSomethingElse() }
for var i = 0; i < 5; ++i { doSomething(i) }
for value in ["a", "b", "c"] { doSomething(value) }
while true { doSomething() }

There are two main types of control statements: loops and branching. For loops run for a specified number of times, and while loops run until a given condition evaluates to false. If statements allow branching based on a given condition. A switch statement is essentially a complex if statement.

If statements

// Simple if-statement
var ballsInAir = 5
if ballsInAir > 1 {
  println("Happy juggling!")

// More complex if-elseif-else statement
if ballsInAir > 1 {
  println("Happy juggling!")
} else if ballsInAir > 10 {
  println("You must be a professional juggler")
} else {
  println("Maybe you should take juggling lessons")

Switch statement

let testedValue = 42
switch testedValue {
  case 0:
    println("The value is empty")
  case 1...50:
    println("Good choice")
    println("Number not in range")

All possible values for the object being tested in the switch statement must be accounted for, or the compiler will generate an error. The easiest way to handle this is by including a "default" case, which will be run for any values that you did not explicitly declare.

For loops

// Standard For loop
// for initialization; condition; modifier { statements }
for var count = 0; count < 30; ++count {

// For-in loop
let suits = ["Clubs", "Diamonds", "Hearts", "Spades"]
for suit in suits {
  println("The next suit is \(suit)")

While loops

// Standard While loop - condition evaluated at top of loop
var entry = 5
while entry < 10 {

// Do-While loop - condition evaluated at end of loop
var entry = 5
do {
} while entry < 10

In the standard while loop, the condition is evaluated first, and the block is only executed if the condition is true. A Do-While loop, on the other hand, executes the block at least once no matter what, because the condition is not checked until after the first pass.