Challenge - 5 Problems
Swift Closure Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Look at how the closure multiplies each number by 2.
✗ Incorrect
The closure takes each number and returns it multiplied by 2, so the map function produces a new array with doubled values.
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
The closure sorts names in descending order.
✗ Incorrect
The closure compares two names and returns true if the first is greater than the second, so the array is sorted in reverse alphabetical order.
🔧 Debug
advanced2: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)
Attempts:
2 left
💡 Hint
Check if all braces are properly closed.
✗ Incorrect
The closure is missing a closing brace '}', causing a syntax error.
❓ Predict Output
advanced2: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())
Attempts:
2 left
💡 Hint
The closure captures and updates 'total' each time it is called.
✗ Incorrect
The closure remembers the 'total' variable and adds 'amount' each call, so first call returns 10, second returns 20.
🧠 Conceptual
expert2:00remaining
Which option correctly explains trailing closure syntax?
In Swift, which statement best describes the trailing closure syntax?
Attempts:
2 left
💡 Hint
Think about how you can write closures after function calls.
✗ Incorrect
Trailing closure syntax lets you write a closure outside the parentheses if it is the last argument, making code cleaner.