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📝 Application Q15 of 15
Swift - Functions
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.
Afunc makeAdder(_ x: Int) -> Int {
func adder(y: Int) -> Int {
return x + y
}
return adder(5)
}
Bfunc makeAdder(_ x: Int) -> (Int) -> Int {
func adder(y: Int) -> Int {
return x + y
}
return adder
}
Cfunc makeAdder(_ x: Int) -> (Int) -> Int {
return func(y: Int) -> Int { x + y }
}
Dfunc makeAdder(_ x: Int) -> (Int) -> Int {
func adder(y: Int) -> Int {
return y
}
return adder
}
Step-by-Step Solution
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]
Quick Trick: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
Master "Functions" in Swift
9 interactive learning modes - each teaches the same concept differently