Bird
0
0

Identify the error in this operator overloading code:

medium📝 Debug Q6 of 15
Swift - Operators and Expressions
Identify the error in this operator overloading code:
struct Box {
    var size: Int
    static func + (lhs: Box, rhs: Box) -> Int {
        return lhs.size + rhs.size
    }
}
AReturn type should be Box, not Int
BOperator + cannot be overloaded for structs
CParameters should be inout
DMissing mutating keyword
Step-by-Step Solution
Solution:
  1. Step 1: Check operator + return type

    Operator + usually returns the same type as operands to allow chaining.
  2. Step 2: Identify mismatch

    Here it returns Int instead of Box, which breaks expected usage.
  3. Final Answer:

    Return type should be Box, not Int -> Option A
  4. Quick Check:

    Operator + return type = same as struct [OK]
Quick Trick: Operator + should return the struct type for chaining [OK]
Common Mistakes:
  • Returning different type
  • Thinking structs can't overload operators
  • Using inout unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes