Consider this Swift function that takes a closure as a parameter and calls it:
func greetUser(name: String, action: (String) -> String) {
let message = action(name)
print(message)
}
greetUser(name: "Anna") { userName in
return "Hello, \(userName)!"
}What will be printed when this code runs?
func greetUser(name: String, action: (String) -> String) { let message = action(name) print(message) } greetUser(name: "Anna") { userName in return "Hello, \(userName)!" }
Look at how the closure uses the parameter userName inside the string.
The closure receives the string "Anna" as userName and returns "Hello, Anna!". This string is printed by the function.
Examine this Swift code that uses a trailing closure syntax:
func performOperation(_ a: Int, _ b: Int, operation: (Int, Int) -> Int) {
let result = operation(a, b)
print(result)
}
performOperation(4, 5) { x, y in
x * y
}What is the output?
func performOperation(_ a: Int, _ b: Int, operation: (Int, Int) -> Int) { let result = operation(a, b) print(result) } performOperation(4, 5) { x, y in x * y }
Remember that the closure multiplies the two numbers.
The closure multiplies 4 and 5, resulting in 20, which is printed.
Look at this Swift function call with a closure parameter:
func calculate(value: Int, operation: (Int) -> Int) {
let result = operation(value)
print(result)
}
calculate(value: 10) { number in
if number > 5 {
number * 2
}
}What error will this code cause when compiled?
func calculate(value: Int, operation: (Int) -> Int) { let result = operation(value) print(result) } calculate(value: 10) { number in if number > 5 { number * 2 } }
Check if the closure always returns a value.
The closure has an if statement but no else branch and no explicit return, so it may not return a value in all cases, causing a compile error.
In Swift, what does it mean when a closure parameter is marked with @escaping?
Think about when the closure might be used relative to the function call.
An escaping closure can be saved and called later, even after the function that received it has finished.
Analyze this Swift code with nested closures passed as parameters:
func outerFunction(action: (Int) -> (Int) -> Int) {
let innerClosure = action(3)
let result = innerClosure(4)
print(result)
}
outerFunction { x in
return { y in
x + y
}
}What will be printed?
func outerFunction(action: (Int) -> (Int) -> Int) { let innerClosure = action(3) let result = innerClosure(4) print(result) } outerFunction { x in return { y in x + y } }
Trace the values of x and y through the closures.
The outer closure receives 3 as x and returns an inner closure that adds x and y. Calling innerClosure(4) adds 3 + 4 = 7.