0
0
Swiftprogramming~20 mins

Trailing closure syntax in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Trailing Closure Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)!"
}
AHello, Alice!
BHello, name!
Cgreet(name: "Alice")
DError: Missing return statement
Attempts:
2 left
💡 Hint
Trailing closures let you write the closure outside the parentheses.
Predict Output
intermediate
2: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
}
AError: Missing parentheses
B7
C12
D34
Attempts:
2 left
💡 Hint
The closure multiplies the two numbers.
🔧 Debug
advanced
2: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")
}
ARuntimeError: Infinite loop
BSyntaxError: Unexpected newline
CTypeError: task is not a function
DNo error, prints "Hello" 3 times
Attempts:
2 left
💡 Hint
Trailing closure syntax is correct here.
Predict Output
advanced
2: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")
}
ASyntaxError: Unexpected token 'completion:'
BAction done\nCompletion done
CRuntimeError: Missing completion closure
DCompletion done\nAction done
Attempts:
2 left
💡 Hint
Swift supports multiple trailing closures with labels.
🧠 Conceptual
expert
2:00remaining
Why use trailing closure syntax?
Which of the following is the main advantage of using trailing closure syntax in Swift?
AIt allows passing closures outside parentheses for cleaner and more readable code.
BIt forces closures to be written inline inside the parentheses.
CIt disables the use of multiple closures in a function call.
DIt automatically converts closures to asynchronous functions.
Attempts:
2 left
💡 Hint
Think about code readability and syntax style.