0
0
Swiftprogramming~3 mins

Why Closures as function parameters in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could change how a function works without rewriting it every time?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
func sortByLength(names: [String]) -> [String] {
  return names.sorted { $0.count < $1.count }
}

let sorted = sortByLength(names: names)
After
let sorted = names.sorted { $0.count < $1.count }
What It Enables

You can customize how functions work on the fly, making your code shorter, clearer, and more flexible.

Real Life Example

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.

Key Takeaways

Closures let you pass custom behavior into functions.

This avoids writing many similar functions.

It makes your code cleaner and easier to change.