0
0
Swiftprogramming~5 mins

Functions as types in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean that functions are types in Swift?
In Swift, functions can be treated like any other type, such as Int or String. This means you can store functions in variables, pass them as arguments, and return them from other functions.
Click to reveal answer
beginner
How do you declare a variable that holds a function taking two Ints and returning an Int?
You declare it like this: var operation: (Int, Int) -> Int. This means operation is a variable that stores a function which takes two Int values and returns an Int.
Click to reveal answer
intermediate
Can you pass a function as a parameter to another function in Swift? How?
Yes! You specify the parameter type as a function type. For example: func performOperation(_ a: Int, _ b: Int, operation: (Int, Int) -> Int) -> Int. Then you can call operation(a, b) inside the function.
Click to reveal answer
intermediate
What is the syntax to return a function from another function in Swift?
You specify the return type as a function type. For example: func makeAdder(_ x: Int) -> (Int) -> Int returns a function that takes an Int and returns an Int.
Click to reveal answer
beginner
Why is treating functions as types useful in Swift?
It allows you to write flexible and reusable code. You can pass behavior around, customize actions, and create powerful abstractions like callbacks and event handlers.
Click to reveal answer
How do you declare a variable that holds a function taking a String and returning Void in Swift?
Avar action: (String) -> Void
Bvar action: String -> Void
Cvar action: (String) => Void
Dvar action: function(String) -> Void
Which of these is a valid way to pass a function as a parameter in Swift?
Afunc run(operation: Int, Int) -> Int {}
Bfunc run(operation: (Int, Int)) {}
Cfunc run(operation: function) {}
Dfunc run(operation: (Int, Int) -> Int) {}
What is the return type of this function? func makeMultiplier() -> (Int) -> Int
AA function that takes an Int and returns an Int
BAn Int value
CA tuple of Ints
DVoid
Can you assign a function to a variable in Swift?
AOnly if the function returns Void
BNo, functions cannot be assigned to variables
CYes, if the variable type matches the function type
DOnly if the function has no parameters
What is the benefit of using functions as types?
AIt makes code run faster
BIt allows passing behavior as data
CIt prevents errors automatically
DIt makes variables immutable
Explain how you can use functions as types to pass a function as an argument in Swift.
Think about how you write the parameter type and how you use it inside the function.
You got /3 concepts.
    Describe how returning a function from another function works and why it might be useful.
    Consider how you can create customized functions on the fly.
    You got /3 concepts.