Closures let you pass small pieces of code into functions to run later. This helps make your code flexible and reusable.
0
0
Closures as function parameters in Swift
Introduction
When you want to run some code after a task finishes, like loading data.
When you want to customize how a function works without changing its code.
When you want to handle events like button taps in your app.
When you want to sort or filter a list with custom rules.
When you want to run code multiple times with different actions.
Syntax
Swift
func functionName(parameterName: (ParameterTypes) -> ReturnType) { // function body parameterName(arguments) // call the closure }
The closure is written as a parameter type using arrow syntax: (input) -> output.
You call the closure inside the function like a normal function.
Examples
This function takes a closure with no inputs and no return. It prints a greeting, then runs the closure.
Swift
func greetUser(action: () -> Void) { print("Hello!") action() } greetUser { print("Welcome to the app!") }
This function takes a closure that receives an integer. It runs the closure multiple times, passing the current count.
Swift
func repeatTask(times: Int, task: (Int) -> Void) { for i in 1...times { task(i) } } repeatTask(times: 3) { count in print("Task number \(count)") }
Sample Program
This program defines a function that takes two numbers and a closure to perform an operation on them. It then prints the result. We call it twice: once to add, once to multiply.
Swift
func performOperation(a: Int, b: Int, operation: (Int, Int) -> Int) { let result = operation(a, b) print("Result: \(result)") } performOperation(a: 5, b: 3) { x, y in x + y } performOperation(a: 5, b: 3) { x, y in x * y }
OutputSuccess
Important Notes
Closures can capture values from their surrounding context.
Trailing closure syntax lets you write the closure outside the parentheses if it is the last parameter.
Closures make your functions more flexible and reusable.
Summary
Closures are blocks of code you can pass into functions as parameters.
They let you customize what a function does without changing its code.
Use closures to run code later, handle events, or customize behavior.