Thuta Learning
AdvancedProgrammingbeginner

Closures

Relax. We'll talk through this in plain words — no textbook voice.

Closure is a block of code you can store in a variable, pass as a function parameter, and run later. Think of it like JavaScript's callbacks/lambdas. You'll find closures in SwiftUI, async callbacks, sorting/filtering, and button actions.

swift
let names = ["Chris", "Alex", "Ewa", "Barry"]

let sortedNames = names.sorted { first, second in
    first < second
}

let shortNames = names.filter { name in
    name.count <= 4
}

print(sortedNames)
print(shortNames)

sorted tells it how to compare two items. The closure inside filter decides whether to keep or drop each item.

You should see
["Alex", "Barry", "Chris", "Ewa"] ["Alex", "Ewa"]

Easy traps

  • When the logic inside a closure gets complex and the return type isn't obvious, splitting it into its own function makes it easier to read.
Closures | Thuta Learning