Bird
0
0

What will be the output of the following Swift code?

medium📝 Predict Output Q4 of 15
Swift - Operators and Expressions
What will be the output of the following Swift code?
struct Counter {
    var value: Int
    static func + (lhs: Counter, rhs: Counter) -> Counter {
        return Counter(value: lhs.value + rhs.value)
    }
}
let a = Counter(value: 3)
let b = Counter(value: 7)
let c = a + b
print(c.value)
A37
BError: Operator + not defined
C10
D0
Step-by-Step Solution
Solution:
  1. Step 1: Understand operator + overload

    The + operator adds the value properties of two Counter instances.
  2. Step 2: Calculate the result

    a.value is 3, b.value is 7, so c.value = 3 + 7 = 10.
  3. Final Answer:

    10 -> Option C
  4. Quick Check:

    Operator + overload sums values = 10 [OK]
Quick Trick: Overloaded + adds values inside structs [OK]
Common Mistakes:
  • Expecting string concatenation
  • Thinking operator is undefined
  • Confusing values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes