0
0
Swiftprogramming~20 mins

Closure expression syntax in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Closure Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this closure expression?
Consider the following Swift code using a closure expression. What will be printed when this code runs?
Swift
let numbers = [1, 2, 3, 4]
let doubled = numbers.map({ (num: Int) -> Int in
    return num * 2
})
print(doubled)
A[4, 8, 12, 16]
B[1, 2, 3, 4]
CCompilation error
D[2, 4, 6, 8]
Attempts:
2 left
💡 Hint
Look at how the closure multiplies each number by 2.
Predict Output
intermediate
2:00remaining
What does this shorthand closure print?
What is the output of this Swift code using shorthand argument names in a closure?
Swift
let names = ["Anna", "Alex", "Brian", "Jack"]
let sortedNames = names.sorted(by: { $0 > $1 })
print(sortedNames)
A["Jack", "Brian", "Alex", "Anna"]
BRuntime error
C["Alex", "Anna", "Brian", "Jack"]
D["Anna", "Alex", "Brian", "Jack"]
Attempts:
2 left
💡 Hint
The closure sorts names in descending order.
🔧 Debug
advanced
2:00remaining
Identify the error in this closure syntax
This Swift code tries to filter an array using a closure but causes a compile error. What is the error?
Swift
let numbers = [1, 2, 3, 4, 5]
let evens = numbers.filter { num in
    num % 2 == 0
}

print(evens)
AMissing closing brace '}' for the closure
BMissing return keyword inside the closure
CIncorrect use of parentheses in filter call
DUsing 'num' instead of '$0' causes error
Attempts:
2 left
💡 Hint
Check if all braces are properly closed.
Predict Output
advanced
2:00remaining
What is the output of this nested closure?
What will this Swift code print when run?
Swift
func makeIncrementer(amount: Int) -> () -> Int {
    var total = 0
    return {
        total += amount
        return total
    }
}

let incrementByTen = makeIncrementer(amount: 10)
print(incrementByTen())
print(incrementByTen())
A0\n10
BCompilation error
C10\n20
D10\n10
Attempts:
2 left
💡 Hint
The closure captures and updates 'total' each time it is called.
🧠 Conceptual
expert
2:00remaining
Which option correctly explains trailing closure syntax?
In Swift, which statement best describes the trailing closure syntax?
ATrailing closures must always have explicit parameter types declared.
BA closure passed as the last argument can be written outside the parentheses of the function call.
CTrailing closures cannot capture variables from the surrounding context.
DTrailing closures are only allowed if the function has exactly one parameter.
Attempts:
2 left
💡 Hint
Think about how you can write closures after function calls.