Bird
0
0

Given the following code:

hard📝 Application Q9 of 15
Swift - Operators and Expressions
Given the following code:
class Box {
    var value: Int
    init(_ value: Int) { self.value = value }
}

let box1 = Box(5)
let box2 = Box(5)
let box3 = box1

if box1 === box3 {
    print("Same box")
}
if box1 === box2 {
    print("Same box")
}

What will be printed?
ASame box
BSame box\nSame box
CNo output
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze identity comparisons

    box1 and box3 refer to the same instance, so box1 === box3 is true and prints "Same box".
  2. Step 2: Check box1 and box2

    box1 and box2 are different instances with same value, so box1 === box2 is false and does not print.
  3. Final Answer:

    Same box -> Option A
  4. Quick Check:

    === compares instance identity, not value [OK]
Quick Trick: === checks if two variables point to the same object [OK]
Common Mistakes:
  • Assuming same value means same instance
  • Expecting both prints to run
  • Confusing === with ==

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes