Bird
0
0

Consider this code snippet:

medium📝 Predict Output Q5 of 15
Swift - Operators and Expressions
Consider this code snippet:
struct Vector {
    var x: Int
    var y: Int
    static func * (lhs: Vector, rhs: Int) -> Vector {
        return Vector(x: lhs.x * rhs, y: lhs.y * rhs)
    }
}
let v = Vector(x: 2, y: 3)
let result = v * 4
print(result.x, result.y)

What is the output?
A6 12
B8 12
C2 3
DError: Operator * not defined for Vector and Int
Step-by-Step Solution
Solution:
  1. Step 1: Analyze operator * overload

    The operator multiplies each component of Vector by the integer rhs.
  2. Step 2: Calculate output values

    v.x = 2 * 4 = 8, v.y = 3 * 4 = 12, so output is "8 12".
  3. Final Answer:

    8 12 -> Option B
  4. Quick Check:

    Vector * Int multiplies components = 8 12 [OK]
Quick Trick: Operator * can multiply struct fields by Int [OK]
Common Mistakes:
  • Assuming no operator for Vector and Int
  • Mixing up multiplication
  • Printing original values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes