Bird
0
0

What will this Swift code print?

medium📝 Predict Output Q5 of 15
Swift - Functions
What will this Swift code print?
func add(_ a: Int, _ b: Int = 5) -> Int {
    return a + b
}
print(add(3))
print(add(3, 4))
A8\n8
B3\n7
CError: Missing argument for 'b'
D8\n7
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate first function call

    add(3) uses default b=5, so returns 3+5=8.
  2. Step 2: Evaluate second function call

    add(3,4) uses b=4 explicitly, returns 3+4=7.
  3. Final Answer:

    8\n7 -> Option D
  4. Quick Check:

    Default parameter used only if argument omitted [OK]
Quick Trick: Default used only when argument is missing [OK]
Common Mistakes:
  • Assuming default always used
  • Expecting error on missing argument
  • Mixing up return values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes