Challenge - 5 Problems
Swift Closure Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift closure example?
Consider this Swift code that uses a closure to add two numbers. What will be printed?
Swift
let add: (Int, Int) -> Int = { (a, b) in a + b } print(add(3, 5))
Attempts:
2 left
💡 Hint
Closures can be assigned to variables and called like functions.
✗ Incorrect
The closure adds 3 and 5, so the output is 8.
🧠 Conceptual
intermediate1:30remaining
Why are closures fundamental in Swift?
Which of these best explains why closures are fundamental in Swift?
Attempts:
2 left
💡 Hint
Think about how closures can remember values from where they were created.
✗ Incorrect
Closures can capture values from their surrounding scope, making them powerful for callbacks, event handling, and more.
🔧 Debug
advanced2:00remaining
What error does this closure code produce?
Look at this Swift code using a closure. What error will it cause?
Swift
var counter = 0 let incrementer = { counter += 1 } incrementer() print(counter)
Attempts:
2 left
💡 Hint
Check if the variable is mutable and if the closure modifies it.
✗ Incorrect
The variable counter is mutable (var), so the closure can increment it. The output is 1.
❓ Predict Output
advanced2:30remaining
What is the output of this closure capturing example?
What will this Swift code print?
Swift
func makeIncrementer(amount: Int) -> () -> Int { var total = 0 let incrementer: () -> Int = { total += amount return total } return incrementer } let incrementByTen = makeIncrementer(amount: 10) print(incrementByTen()) print(incrementByTen())
Attempts:
2 left
💡 Hint
Closures can capture and modify variables from their creation context.
✗ Incorrect
The closure captures 'total' and adds 'amount' each time it is called, so outputs are 10 then 20.
🚀 Application
expert2:00remaining
How many items are in the resulting array after using this closure?
What is the count of elements in the array 'results' after running this Swift code?
Swift
let numbers = [1, 2, 3, 4, 5] let results = numbers.map { num in if num % 2 == 0 { return num * 2 } else { return num } } print(results.count)
Attempts:
2 left
💡 Hint
The map function returns an array with the same number of elements as the original.
✗ Incorrect
The map closure transforms each element but keeps the array size the same, so count is 5.