0
0
Swiftprogramming~20 mins

Why closures are fundamental in Swift - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Closure Mastery
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 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))
A8
BError: Missing return statement
C35
D0
Attempts:
2 left
💡 Hint
Closures can be assigned to variables and called like functions.
🧠 Conceptual
intermediate
1:30remaining
Why are closures fundamental in Swift?
Which of these best explains why closures are fundamental in Swift?
AThey are used only to create classes and structs.
BThey are only used for asynchronous programming and have no other use.
CThey replace all functions and methods in Swift.
DThey allow you to write inline, self-contained blocks of code that can capture and store references to variables and constants from the surrounding context.
Attempts:
2 left
💡 Hint
Think about how closures can remember values from where they were created.
🔧 Debug
advanced
2: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)
AError: Cannot assign to value: 'counter' is a 'let' constant
BNo error, prints 1
CError: Closure cannot capture mutable variable
DError: Missing return in closure
Attempts:
2 left
💡 Hint
Check if the variable is mutable and if the closure modifies it.
Predict Output
advanced
2: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())
A
0
10
B
10
10
C
10
20
DError: Cannot capture 'total' in closure
Attempts:
2 left
💡 Hint
Closures can capture and modify variables from their creation context.
🚀 Application
expert
2: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)
A5
B3
C2
D0
Attempts:
2 left
💡 Hint
The map function returns an array with the same number of elements as the original.