What if you could change how a function works without rewriting it every time?
Why Closures as function parameters in Swift? - Purpose & Use Cases
Imagine you want to sort a list of names in different ways, like alphabetically or by length. Without closures, you'd have to write a new sorting function for each way you want to sort.
Writing many separate functions for each small change is slow and confusing. It's easy to make mistakes and hard to keep track of all the different versions.
Closures let you pass little pieces of code directly into functions. This means you can tell a function exactly how to behave without writing a whole new function every time.
func sortByLength(names: [String]) -> [String] {
return names.sorted { $0.count < $1.count }
}
let sorted = sortByLength(names: names)let sorted = names.sorted { $0.count < $1.count }You can customize how functions work on the fly, making your code shorter, clearer, and more flexible.
When building an app, you might want to filter a list of tasks by different rules. Passing closures lets you reuse the same filter function but change the rules easily.
Closures let you pass custom behavior into functions.
This avoids writing many similar functions.
It makes your code cleaner and easier to change.