Activity 1
Sort lesson titles
Sort an array of lesson titles by character count, placing shorter titles first.
Hint: sorted accepts a closure comparing two elements.
Swift Fundamentals
Pass behavior as values, transform collections, and understand captured context.
Before you begin
Learning stage
A closure is a self-contained block of functionality that can be stored and passed around. Functions are named closures; closure expressions provide a compact unnamed syntax.
Closures can capture constants and variables from their surrounding scope. This makes them powerful for callbacks and transformations, but captured references require care in longer-lived asynchronous or stored closures.
Learning stage
The example filters and transforms lesson values with trailing closures.
let minutes = [8, 15, 12, 20]
let longerLessons = minutes.filter { value in
value >= 12
}
let labels = longerLessons.map { "\($0) min" }
let total = minutes.reduce(0) { partial, value in
partial + value
}
print(labels)
print("Total: \(total) min")Learning stage
These concepts appear throughout production iOS code. Focus on the requirement each technique communicates.
Learning stage
Notice these mistakes early so the compiler and type system can help instead of becoming obstacles.
Learning stage
Work through these activities in a small Xcode project. No embedded playground is required on this site.
Activity 1
Sort an array of lesson titles by character count, placing shorter titles first.
Hint: sorted accepts a closure comparing two elements.
Activity 2
Create a variable outside a closure, update it inside a closure, and explain why the closure can access it.
Hint: Start with a synchronous closure so lifecycle and memory are not distractions.
Learning stage
Answer each question before revealing the explanation.
QUESTION 1
A new collection containing the result of transforming each source element.
QUESTION 2
The closure keeps access to a constant or variable from its surrounding context.
Learning stage
Explain the idea in terms of its purpose, behavior, and tradeoffs rather than reciting syntax.
Short answer: A closure is a block of executable behavior that can be stored, passed, and invoked as a value.
Swift functions are closures with names, while closure expressions are unnamed. Closures have parameter and result types, can use trailing syntax, and can capture values from their lexical scope. Stored escaping closures may require deliberate capture semantics.
Possible follow-ups
Learning stage
Closures let APIs receive behavior. Keep them readable, use collection transformations where they express intent, and treat capture lifetime as part of the design.