Bird
0
0

Given this code, what is the correct way to swap two mutable variables a and b in Swift?

hard📝 Application Q9 of 15
Swift - Variables and Constants
Given this code, what is the correct way to swap two mutable variables a and b in Swift?
var a = 5
var b = 10
// Swap a and b here
Alet temp = a temp = b b = temp
Bvar temp = a a = b b = temp
Ca = b b = a
Dvar temp = b b = a a = b
Step-by-Step Solution
Solution:
  1. Step 1: Use a temporary variable to hold one value

    Store a in temp so it is not lost when overwritten.
  2. Step 2: Assign b to a and then temp to b

    This completes the swap correctly.
  3. Final Answer:

    var temp = a a = b b = temp -> Option B
  4. Quick Check:

    Swap needs temp variable to avoid overwriting [OK]
Quick Trick: Use temp variable to swap values safely [OK]
Common Mistakes:
  • Swapping without temp loses data
  • Using let temp then changing it
  • Assigning in wrong order
  • Confusing variable names

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes