Control Flow, Functions and Closures

Harry · 16 Sep 2026 · 16 views
Log in to track your progress and mark lessons complete.

Control flow

for i in 1...5 { print(i) }        // 1 to 5

if score >= 50 { print("Pass") }
else { print("Try again") }

switch grade {
case "A": print("Excellent")
case "B", "C": print("Good")
default: print("Keep going")
}

Functions

Functions take labelled parameters and can return a value. Labels make call sites read like sentences:

func greet(name: String, loudly: Bool = false) -> String {
    let message = "Hello, (name)"
    return loudly ? message.uppercased() : message
}
greet(name: "Ada")               // "Hello, Ada"
greet(name: "Ada", loudly: true) // "HELLO, ADA"

Closures

A closure is a block of code you can pass around like a value – the backbone of Swift's collection methods and asynchronous APIs:

let nums = [3, 1, 2]
let sorted = nums.sorted { a, b in a < b }   // [1, 2, 3]
let doubled = nums.map { $0 * 2 }              // [6, 2, 4]

$0 is shorthand for the first argument. You will use closures constantly in SwiftUI.

Key points

  • for, if/else and switch cover control flow; switch must be exhaustive.
  • Functions have labelled parameters and can supply defaults.
  • Closures are inline function values, often written with trailing-closure syntax.
  • map, filter and sorted take closures.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

Already have an account? Log in