Here, the inner function adds two numbers and the outer function prints the result.
Swift
func calculate() {
func add(a: Int, b: Int) -> Int {
return a + b
}
let result = add(a: 3, b: 4)
print("Sum is \(result)")
}
Sample Program
This program defines an outer function with a nested inner function. It calls the inner function inside the outer one and prints messages before and after.
D. innerFunc() called before its definition causes error
Solution
Step 1: Analyze function call order
The code calls 'innerFunc()' before it is defined inside 'calculate()'. Swift requires functions to be defined before use.
Step 2: Understand Swift's function declaration rules
Calling a nested function before its declaration causes a compile-time error.
Final Answer:
innerFunc() called before its definition causes error -> Option D
Quick Check:
Call before definition = error [OK]
Hint: Define nested functions before calling them [OK]
Common Mistakes:
Assuming nested functions can be called before definition
Thinking missing return type causes error here
Believing nested functions can't be defined inside
5. How can you use nested functions to create a function that returns another function which adds a fixed number to its input?
Choose the correct Swift code.
hard
A. func makeAdder(_ x: Int) -> Int {
func adder(y: Int) -> Int {
return x + y
}
return adder(5)
}
B. func makeAdder(_ x: Int) -> (Int) -> Int {
func adder(y: Int) -> Int {
return x + y
}
return adder
}
C. func makeAdder(_ x: Int) -> (Int) -> Int {
return func(y: Int) -> Int { x + y }
}
D. func makeAdder(_ x: Int) -> (Int) -> Int {
func adder(y: Int) -> Int {
return y
}
return adder
}
Solution
Step 1: Understand the goal
We want a function that returns another function adding a fixed number 'x' to input 'y'.
Step 2: Check each option's logic
func makeAdder(_ x: Int) -> (Int) -> Int {
func adder(y: Int) -> Int {
return x + y
}
return adder
} defines nested 'adder' using 'x' and returns it correctly. func makeAdder(_ x: Int) -> Int {
func adder(y: Int) -> Int {
return x + y
}
return adder(5)
} returns a value, not a function. func makeAdder(_ x: Int) -> (Int) -> Int {
return func(y: Int) -> Int { x + y }
} has invalid syntax. func makeAdder(_ x: Int) -> (Int) -> Int {
func adder(y: Int) -> Int {
return y
}
return adder
} returns a function ignoring 'x'.
Final Answer:
func makeAdder(_ x: Int) -> (Int) -> Int {
func adder(y: Int) -> Int {
return x + y
}
return adder
} -> Option B
Quick Check:
Nested function returns function adding x = func makeAdder(_ x: Int) -> (Int) -> Int {
func adder(y: Int) -> Int {
return x + y
}
return adder
} [OK]
Hint: Return nested function that uses outer parameter [OK]
Common Mistakes:
Returning a value instead of a function
Incorrect nested function syntax
Ignoring outer function parameter inside nested function
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.