0
0
Swiftprogramming~5 mins

Closures as function parameters in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a closure in Swift?
A closure is a 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 pass a closure as a parameter to a function in Swift?
You define the function parameter with a closure type, for example: (Int) -> Int, then you can pass a closure when calling the function.
Click to reveal answer
intermediate
What is the trailing closure syntax in Swift?
If the last parameter of a function is a closure, you can write the closure outside the parentheses when calling the function. This makes the code cleaner and easier to read.
Click to reveal answer
beginner
Why are closures useful as function parameters?
Closures let you customize behavior by passing code to functions. This helps write flexible and reusable code, like sorting or filtering with custom rules.
Click to reveal answer
intermediate
What does it mean that closures can capture values?
Closures can remember and use variables from the place where they were created, even if that place no longer exists when the closure runs.
Click to reveal answer
How do you declare a function in Swift that takes a closure parameter which accepts an Int and returns a String?
Afunc example(closure: (Int) -> String) {}
Bfunc example(closure: String -> Int) {}
Cfunc example(closure: Int) -> String {}
Dfunc example(closure: () -> ()) {}
What is the trailing closure syntax used for in Swift?
ATo declare a closure inside a function
BTo write the closure outside the parentheses when it is the last parameter
CTo capture variables inside a closure
DTo convert a closure to a function
Which of these is a correct way to call a function with a closure parameter using trailing closure syntax?
AdoSomething() { print("Hello") }
BdoSomething({ print("Hello") })
CdoSomething(print("Hello"))
DdoSomething(print) { "Hello" }
What does it mean when a closure 'captures' a variable?
AIt copies the variable to a new function
BIt deletes the variable after use
CIt keeps a reference to the variable from its surrounding context
DIt converts the variable to a constant
Why use closures as function parameters?
ATo store data permanently
BTo make the function run faster
CTo avoid writing functions
DTo customize what the function does with code you provide
Explain how to define and use a closure as a function parameter in Swift.
Think about how you write the function signature and how you call it with a closure.
You got /3 concepts.
    Describe what it means that closures capture values and why this is useful.
    Imagine a closure remembering something from where it was created.
    You got /3 concepts.