SwSwift · Lesson 3 of 8

Functions & Control Flow

Swift function signatures read like sentences — argument labels are part of the design. Plus switch, which is so capable it replaces most if-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)")
}
◆ Note
Swift switch statements must cover every possible value — add default or cover all cases. Combined with enums (next lesson) the compiler literally tells you when you forgot to handle a case.