Hint: Calling assigned function runs original logic [OK]
Common Mistakes:
Expecting variable to hold result, not function
Confusing function name with string output
Thinking assignment causes error
4. Identify the error in this Swift code snippet:
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
let sum = add(3, 4)
let operation = add(3, 4)
print(operation(5, 6))
medium
A. Function add is not defined properly
B. Missing return statement in add function
C. Cannot assign function call to a constant
D. Cannot call operation as a function because it holds an Int, not a function
Solution
Step 1: Analyze variable assignments
sum is assigned the result of add(3, 4), which is an Int (7). operation is also assigned add(3, 4), so operation is an Int, not a function.
Step 2: Check the call to operation(5, 6)
Since operation is an Int, calling operation(5, 6) causes an error because Int is not callable.
Final Answer:
Cannot call operation as a function because it holds an Int, not a function -> Option D
Quick Check:
Calling Int as function causes error = Cannot call operation as a function because it holds an Int, not a function [OK]
Hint: Assign function name, not function call, to variable [OK]
Common Mistakes:
Assigning function call instead of function reference
Expecting function call to be callable again
Ignoring type mismatch errors
5. How can you write a Swift function that returns another function which adds a fixed number to its input? For example, calling makeAdder(3)(5) should return 8.
hard
A. func makeAdder(_ x: Int) -> (Int) -> Int {
return { y in x + y }
}
B. func makeAdder(_ x: Int) -> Int {
return x + y
}
C. func makeAdder(x: Int, y: Int) -> Int {
return x + y
}
D. func makeAdder(_ x: Int) -> (Int) {
return x
}
Solution
Step 1: Understand the requirement for returning a function
The function makeAdder must return another function that takes an Int and adds it to x.
Step 2: Check which option returns a function type
func makeAdder(_ x: Int) -> (Int) -> Int {
return { y in x + y }
} returns a closure (function) of type (Int) -> Int that adds x and y, matching the requirement.
Final Answer:
func makeAdder(_ x: Int) -> (Int) -> Int {
return { y in x + y }
} -> Option A
Quick Check:
Return function adding x to input = func makeAdder(_ x: Int) -> (Int) -> Int {
return { y in x + y }
} [OK]
Hint: Return a closure capturing x to add later [OK]
Common Mistakes:
Returning Int instead of function
Not using closure syntax for returned function
Incorrect function signature
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.