A closure is a self-contained block of code that can be passed around and used in your code. It can capture and store references to variables and constants from the context where it was created.
Click to reveal answer
intermediate
How do closures help with asynchronous tasks in Swift?
Closures let you write code that runs later, like after a network call finishes. This helps keep your app responsive by not blocking the main thread.
Click to reveal answer
intermediate
Why can closures capture variables from their surrounding context?
Closures can capture variables because they keep a reference to those variables even after the original scope ends. This allows the closure to use and modify those variables later.
Click to reveal answer
beginner
What is a common use case of closures in Swift's standard library?
Closures are often used in functions like map, filter, and reduce to transform or filter collections in a clean and readable way.
Click to reveal answer
beginner
How do closures improve code readability and reusability in Swift?
Closures let you write small chunks of code inline, making your code easier to read and reuse without creating separate functions.
Click to reveal answer
What can a closure in Swift capture from its surrounding context?
AVariables and constants
BOnly constants
COnly variables
DNothing from the context
✗ Incorrect
Closures can capture both variables and constants from the surrounding context.
Which Swift feature commonly uses closures to handle tasks that happen later?
ASynchronous loops
BAsynchronous callbacks
CStatic typing
DClass inheritance
✗ Incorrect
Closures are used for asynchronous callbacks to run code after a task finishes.
Which of these Swift functions typically takes a closure as an argument?
Aprint
Binit
Cmap
Ddeinit
✗ Incorrect
The map function takes a closure to transform each element in a collection.
Why are closures considered fundamental in Swift?
AThey allow code to be passed and executed later
BThey replace all functions
CThey are only used for UI design
DThey prevent variable capture
✗ Incorrect
Closures allow you to pass code around and execute it later, which is key for many Swift features.
What happens to variables captured by a closure after the original scope ends?
AThey cause an error
BThey are deleted immediately
CThey become constants
DThey stay alive and can be used by the closure
✗ Incorrect
Captured variables stay alive as long as the closure exists, allowing the closure to use them.
Explain in your own words why closures are important in Swift programming.
Think about how closures let you save and run code later, and how they keep variables alive.
You got /4 concepts.
Describe a simple example where a closure improves code readability in Swift.
Consider how closures help when working with lists or arrays.
You got /4 concepts.
Practice
(1/5)
1. What is a closure in Swift? Closures are best described as:
easy
A. A type of variable that stores numbers
B. Blocks of code that can be saved and used later
C. A special kind of loop
D. A way to declare constants
Solution
Step 1: Understand the definition of closures
Closures are self-contained blocks of functionality that can be passed around and used in your code.
Step 2: Match the description to the options
Blocks of code that can be saved and used later correctly describes closures as blocks of code saved for later use, unlike variables, loops, or constants.
Final Answer:
Blocks of code that can be saved and used later -> Option B
Quick Check:
Closure = reusable code block [OK]
Hint: Closures are like saved recipes for code [OK]
Common Mistakes:
Confusing closures with variables
Thinking closures are loops
Mixing closures with constants
2. Which of the following is the correct syntax to declare a closure that explicitly takes no parameters and returns an Int?
easy
A. let closure = { () -> Int in return 5 }
B. let closure = (Int) -> { 5 }
C. let closure = { return 5 }
D. let closure = func() -> Int { 5 }
Solution
Step 1: Recall closure syntax in Swift
A closure with no parameters and returning Int is declared as { () -> Int in ... }.
Step 2: Check each option
let closure = { () -> Int in return 5 } matches the correct syntax. let closure = { return 5 } misses return type and parameters. let closure = (Int) -> { 5 } is invalid syntax. let closure = func() -> Int { 5 } uses function syntax, not closure.
Final Answer:
let closure = { () -> Int in return 5 } -> Option A
Hint: Closure syntax uses braces with 'in' keyword [OK]
Common Mistakes:
Omitting 'in' keyword
Using function syntax instead of closure
Missing return type when needed
3. What will be printed by this Swift code?
let multiplyByTwo = { (number: Int) -> Int in
return number * 2
}
print(multiplyByTwo(4))
medium
A. Error
B. 4
C. 2
D. 8
Solution
Step 1: Understand the closure behavior
The closure takes an Int and returns that number multiplied by 2.
Step 2: Calculate the output for input 4
4 * 2 = 8, so the print statement outputs 8.
Final Answer:
8 -> Option D
Quick Check:
4 * 2 = 8 [OK]
Hint: Multiply input by 2 inside closure [OK]
Common Mistakes:
Confusing input and output values
Expecting the closure to print automatically
Syntax errors in closure call
4. Identify the error in this closure declaration:
let greet = { name: String in
print("Hello, \(name)!")
}
medium
A. Missing parentheses around parameters
B. Missing 'in' keyword
C. Closure must return a value
D. Incorrect print syntax
Solution
Step 1: Check closure parameter syntax
Closure parameters must include types inside parentheses, like (name: String).
Step 2: Identify the error in given code
The code misses parentheses around parameters.
Final Answer:
Missing parentheses around parameters -> Option A
Quick Check:
Parameters need types in parentheses [OK]
Hint: Always put parameters and types in parentheses [OK]
Common Mistakes:
Omitting parentheses around parameters
Forgetting parameter types
Assuming closures must return values
5. How can closures capture values from their surrounding context? Consider this code:
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())
What will be the output?
hard
A. 0 and 10
B. 10 and 10
C. 10 and 20
D. Error because total is not accessible
Solution
Step 1: Understand closure capturing
The closure captures the variable 'total' from its surrounding context and modifies it each time it runs.
Step 2: Trace the output of two calls
First call adds 10 to total (0 + 10 = 10), second call adds 10 again (10 + 10 = 20).
Final Answer:
10 and 20 -> Option C
Quick Check:
Closures capture and update variables [OK]
Hint: Closures remember and update outside variables [OK]
Common Mistakes:
Assuming closures do not keep state
Thinking total resets each call
Expecting errors due to variable scope
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.