Bird
0
0

How do you correctly overload the - operator for a struct named Distance in Swift?

easy📝 Syntax Q3 of 15
Swift - Operators and Expressions
How do you correctly overload the - operator for a struct named Distance in Swift?
Astatic func - (lhs: Distance, rhs: Distance) -> Distance { return Distance(value: lhs.value - rhs.value) }
Bfunc - (lhs: Distance, rhs: Distance) -> Distance { return Distance(value: lhs.value - rhs.value) }
Cstatic func subtract(lhs: Distance, rhs: Distance) -> Distance { return Distance(value: lhs.value - rhs.value) }
Dfunc subtract(lhs: Distance, rhs: Distance) -> Distance { return Distance(value: lhs.value - rhs.value) }
Step-by-Step Solution
Solution:
  1. Step 1: Declare the operator function as static

    Operator overloads must be static methods inside the struct.
  2. Step 2: Use the correct operator symbol and parameters

    The function must be named with the operator symbol (-) and take two parameters of type Distance.
  3. Step 3: Return a new Distance instance

    The function returns a new Distance with the value calculated by subtracting rhs.value from lhs.value.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Static + operator symbol + correct parameters [OK]
Quick Trick: Operator overloads are static functions with operator symbol [OK]
Common Mistakes:
  • Forgetting to declare the function as static
  • Using a custom function name instead of the operator symbol
  • Defining the function as an instance method instead of static

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes