Bird
0
0

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:
  1. Step 1: Understand the goal

    We want a function that returns another function adding a fixed number 'x' to input 'y'.
  2. 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'.
  3. Final Answer:

    func makeAdder(_ x: Int) -> (Int) -> Int { func adder(y: Int) -> Int { return x + y } return adder } -> Option B
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes