Challenge - 5 Problems
Trailing Closure Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of trailing closure with single parameter
What is the output of this Swift code using trailing closure syntax?
Swift
func greet(name: String, action: (String) -> String) { print(action(name)) } greet(name: "Alice") { name in "Hello, \(name)!" }
Attempts:
2 left
💡 Hint
Trailing closures let you write the closure outside the parentheses.
✗ Incorrect
The function greet takes a name and a closure that returns a greeting string. The trailing closure syntax passes the closure after the function call parentheses. The closure returns "Hello, Alice!" which is printed.
❓ Predict Output
intermediate2:00remaining
Trailing closure with multiple parameters
What will be printed by this Swift code using trailing closure syntax?
Swift
func combine(_ a: Int, _ b: Int, operation: (Int, Int) -> Int) { print(operation(a, b)) } combine(3, 4) { x, y in x * y }
Attempts:
2 left
💡 Hint
The closure multiplies the two numbers.
✗ Incorrect
The combine function takes two integers and a closure that returns an integer. The trailing closure multiplies 3 and 4, resulting in 12, which is printed.
🔧 Debug
advanced2:00remaining
Identify the error in trailing closure usage
What error does this Swift code produce?
Swift
func repeatTask(times: Int, task: () -> Void) { for _ in 0..<times { task() } } repeatTask(times: 3) { print("Hello") }
Attempts:
2 left
💡 Hint
Trailing closure syntax is correct here.
✗ Incorrect
The code correctly uses trailing closure syntax to pass a closure that prints "Hello". The function calls the closure 3 times, printing "Hello" 3 times without error.
❓ Predict Output
advanced2:00remaining
Trailing closure with multiple closures
What is the output of this Swift code with multiple trailing closures?
Swift
func perform(action: () -> Void, completion: () -> Void) { action() completion() } perform { print("Action done") } completion: { print("Completion done") }
Attempts:
2 left
💡 Hint
Swift supports multiple trailing closures with labels.
✗ Incorrect
The perform function takes two closures. The first trailing closure is for action, the second labeled trailing closure is for completion. The output prints "Action done" then "Completion done".
🧠 Conceptual
expert2:00remaining
Why use trailing closure syntax?
Which of the following is the main advantage of using trailing closure syntax in Swift?
Attempts:
2 left
💡 Hint
Think about code readability and syntax style.
✗ Incorrect
Trailing closure syntax lets you write a closure after the function call parentheses, making code cleaner and easier to read, especially when the closure is long or the last argument.