0
0
Swiftprogramming~5 mins

Closure expression syntax in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a closure expression in Swift?
A closure expression is a short, unnamed block of code that can be passed around and used in your code. It can capture values from its surrounding context.
Click to reveal answer
beginner
How do you write a simple closure expression that adds two numbers in Swift?
You can write it like this: <br>
{ (a: Int, b: Int) -> Int in<br>  return a + b<br>}
Click to reveal answer
beginner
What does the 'in' keyword do in a closure expression?
The 'in' keyword separates the closure's parameters and return type from the body of the closure.
Click to reveal answer
intermediate
How can you simplify a closure expression in Swift?
You can omit parameter types, return type, and even the 'return' keyword if the closure has a single expression. Swift can infer these automatically.
Click to reveal answer
intermediate
What are shorthand argument names in closure expressions?
Shorthand argument names like $0, $1 let you refer to closure parameters without naming them explicitly, making the closure shorter and cleaner.
Click to reveal answer
What keyword separates parameters from the body in a Swift closure expression?
Alet
Bin
Creturn
Dfunc
Which of these is a valid way to write a closure that adds two Ints in Swift?
Aclosure add(a: Int, b: Int) { return a + b }
Bfunc add(a: Int, b: Int) { a + b }
Clet add = (a, b) => a + b
D{ (a: Int, b: Int) -> Int in return a + b }
How can you refer to the first parameter in a closure without naming it?
A$0
Bparam1
Cfirst
Darg1
What can Swift infer in a closure expression to simplify the syntax?
AFunction names
BVariable names
CParameter types and return type
DClass names
Which of the following is NOT true about closure expressions in Swift?
AThey must always have explicit parameter types
BThey can capture values from their surrounding context
CThey can be assigned to variables
DThey can be passed as arguments to functions
Explain the basic syntax of a closure expression in Swift and the role of the 'in' keyword.
Think about how you separate inputs from the code inside.
You got /4 concepts.
    Describe how you can simplify closure expressions using Swift's type inference and shorthand argument names.
    Swift helps you write less code by guessing types and letting you skip names.
    You got /4 concepts.