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"]