Recall & Review
beginner
What is a function in Swift?
A function is a reusable block of code that performs a specific task. It can take inputs, called parameters, and can return a value.
Click to reveal answer
beginner
What is a closure in Swift?
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 surrounding context.
Click to reveal answer
beginner
How do you declare a simple function that adds two numbers in Swift?
func add(a: Int, b: Int) -> Int {
return a + b
}
Click to reveal answer
intermediate
What does it mean that closures can "capture" values?
Closures can remember and use constants and variables from the place where they were created, even if that place no longer exists when the closure is called.
Click to reveal answer
intermediate
How can you write a closure that multiplies two numbers and assign it to a variable?
let multiply = { (a: Int, b: Int) -> Int in
return a * b
}Click to reveal answer
Which keyword is used to define a function in Swift?
✗ Incorrect
In Swift, the keyword to define a function is func.
What is a closure in Swift?
✗ Incorrect
A closure is a block of code that can be passed around and used later.
How do closures capture values?
✗ Incorrect
Closures capture values by referencing variables from their surrounding context.
Which of the following is the correct syntax for a closure that adds two Ints?
✗ Incorrect
The correct closure syntax uses curly braces and the 'in' keyword: let add = { (a: Int, b: Int) -> Int in return a + b }.
What keyword is used inside a closure to separate parameters from the body?
✗ Incorrect
The keyword in separates the closure's parameters and return type from its body.
Explain in your own words what a closure is and how it differs from a function in Swift.
Think about how closures can remember variables from where they were created.
You got /3 concepts.
Write a simple Swift function and a closure that both add two numbers. Describe their syntax differences.
Remember functions use 'func' keyword; closures use curly braces and 'in'.
You got /4 concepts.