Lesson 3 of 8

Functions & Control Flow

Learn how to write with labels, and how to branch with if and switch. Swift's switch can match ranges and patterns, so it often replaces long if-else chains.

Swift
// Argument labels make call sites readable:
func greet(person: String, from hometown: String) -> String {
    return "Hello \(person) from \(hometown)!"
}
greet(person: "Ada", from: "London")

// _ removes the label; defaults work as expected:
func power(_ base: Int, to exponent: Int = 2) -> Int {
    var result = 1
    for _ in 0..<exponent { result *= base }
    return result
}
power(3)          // 9
power(2, to: 10)  // 1024

// Single-expression functions return implicitly:
func double(_ n: Int) -> Int { n * 2 }
Swift
let grade = 87

// Ranges: ..< excludes the end, ... includes it
for i in 1...5 { print(i) }      // 1 2 3 4 5
for i in 0..<3 { print(i) }      // 0 1 2

// switch: no fallthrough, must be exhaustive,
// matches ranges, tuples, and patterns:
switch grade {
case 90...100:
    print("A")
case 80..<90:
    print("B")
case let g where g >= 70:
    print("C — specifically \(g)")
default:
    print("study time")
}

let point = (x: 3, y: 0)
switch point {
case (0, 0):        print("origin")
case (_, 0):        print("on the x-axis")
case (0, _):        print("on the y-axis")
case (let x, let y): print("at \(x), \(y)")
}
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.