Closures let you pass small pieces of code into functions to run later. This helps make your code flexible and reusable.
Closures as function parameters in 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.
func greetUser(action: () -> Void) { print("Hello!") action() } greetUser { print("Welcome to the app!") }
func repeatTask(times: Int, task: (Int) -> Void) { for i in 1...times { task(i) } } repeatTask(times: 3) { count in print("Task number \(count)") }
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.
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 }
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.
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.
Practice
What is the main purpose of passing a closure as a function parameter in Swift?
Solution
Step 1: Understand what a closure is
A closure is a block of code that can be passed around and executed later.Step 2: Understand why closures are passed to functions
Passing a closure lets the function run custom code without changing its own code.Final Answer:
To allow the function to execute custom code provided by the caller -> Option AQuick Check:
Closures customize function behavior = A [OK]
- Thinking closures speed up the function
- Confusing closures with variables
- Believing closures stop function returns
Which of the following is the correct syntax to declare a function that takes a closure parameter with no input and no return value?
func performAction(____) { }Solution
Step 1: Recall closure syntax in Swift
A closure with no input and no return is written as () -> Void.Step 2: Match syntax to function parameter
The parameter should be named and typed as action: () -> Void.Final Answer:
action: () -> Void -> Option DQuick Check:
Closure type syntax = D [OK]
- Using 'Void -> ()' which is invalid
- Adding extra arrows like '() -> () -> Void'
- Using '=>' which is not Swift syntax
What will be printed when the following Swift code runs?
func greet(action: () -> String) {
print("Greeting: " + action())
}
greet { "Hello, Swift!" }Solution
Step 1: Understand the function call
The function greet takes a closure that returns a String and prints "Greeting: " plus the closure's result.Step 2: Evaluate the closure passed
The closure returns "Hello, Swift!", so the print statement outputs "Greeting: Hello, Swift!".Final Answer:
Greeting: Hello, Swift! -> Option CQuick Check:
Closure returns string printed with prefix = A [OK]
- Expecting just the closure string without prefix
- Confusing closure name with output
- Thinking code causes error
Identify the error in this Swift function that takes a closure parameter:
func repeatTask(times: Int, task: () -> Void) {
for _ in 1...times {
task
}
}Solution
Step 1: Check how the closure is used inside the loop
The code uses 'task' without parentheses, so the closure is not executed.Step 2: Correct closure call syntax
To run the closure, it must be called as 'task()' with parentheses.Final Answer:
The closure 'task' is not called with parentheses -> Option AQuick Check:
Call closure with () to execute = C [OK]
- Forgetting parentheses to call closure
- Changing loop range unnecessarily
- Expecting closure to return value when void
Given this function that filters numbers using a closure, how would you call it to get only even numbers?
func filterNumbers(_ numbers: [Int], using condition: (Int) -> Bool) -> [Int] {
var result = [Int]()
for number in numbers {
if condition(number) {
result.append(number)
}
}
return result
}Choose the correct call:
Solution
Step 1: Understand the closure parameter
The closure takes an Int and returns Bool to decide if number is included.Step 2: Identify condition for even numbers
Even numbers satisfy number % 2 == 0, so closure should return true for those.Step 3: Match correct call
filterNumbers([1,2,3,4]) { $0 % 2 == 0 } uses shorthand $0 % 2 == 0, which returns true for even numbers.Final Answer:
filterNumbers([1,2,3,4]) { $0 % 2 == 0 } -> Option BQuick Check:
Closure returns true for even numbers = B [OK]
- Returning number * 2 instead of Bool
- Returning always true to get all numbers
- Filtering numbers greater than 5 instead of even
Ready to prove it?
Pass the test and this pattern moves unknown
