0
0
iOS Swiftmobile~5 mins

Functions and closures in iOS Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Adef
Bfunction
Cmethod
Dfunc
What is a closure in Swift?
AA block of code that can be passed around and used later
BA type of variable
CA class method
DA Swift keyword
How do closures capture values?
ABy copying variables from outside their scope
BBy referencing variables from their surrounding context
CClosures cannot capture values
DBy passing variables as parameters only
Which of the following is the correct syntax for a closure that adds two Ints?
Alet add = { (a: Int, b: Int) -> Int in return a + b }
Bclosure add(a: Int, b: Int) { return a + b }
Cfunc add(a: Int, b: Int) -> Int { return a + b }
Dlet add = (a: Int, b: Int) -> Int { return a + b }
What keyword is used inside a closure to separate parameters from the body?
Athen
Bdo
Cin
Dwhere
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.