Bird
0
0

Examine this Swift code:

hard📝 Application Q9 of 15
Swift - Functions
Examine this Swift code:
func createAdder(_ base: Int) -> (Int) -> Int {
    return { value in base + value }
}

let addFive = createAdder(5)
print(addFive(10))

What programming concept is illustrated here and what will be printed?
AFunction overloading; prints 5
BClosure capturing external variable; prints 15
CRecursion; prints 10
DProtocol conformance; prints 0
Step-by-Step Solution
Solution:
  1. Step 1: Identify the returned function

    The function createAdder returns a closure that adds base to its input.
  2. Step 2: Understand closure capturing

    The closure captures the base variable from its surrounding context.
  3. Step 3: Calculate output

    Calling addFive(10) adds 5 + 10 = 15.
  4. Final Answer:

    Closure capturing external variable; prints 15 -> Option B
  5. Quick Check:

    Closures capture context variables [OK]
Quick Trick: Closures capture variables from surrounding scope [OK]
Common Mistakes:
  • Confusing closure with recursion
  • Assuming function overloading is used
  • Ignoring captured variables in closures

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes