ProgrammingMiddle iOS Developer

How do operator functions (overloading operators as functions) work in Swift? What limitations exist with overloads, and can you create your own operators?

Pass interviews with Hintsage AI assistant

Answer.

Operator functions in Swift are the ability to implement or override standard operators (+, -, *, ==, <, etc.), as well as create your own operators (for example, %% or <|>). This is done using the operator keyword in the function declaration. Typically, operators are overloaded for working with custom types to make them syntactically convenient and intuitive.

Example of overloading addition for the Vector2D structure:

struct Vector2D { var x: Double var y: Double } func + (lhs: Vector2D, rhs: Vector2D) -> Vector2D { return Vector2D(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } let v1 = Vector2D(x: 1, y: 2) let v2 = Vector2D(x: 3, y: 4) let sum = v1 + v2 // Vector2D(x: 4, y: 6)

Limitations:

  • Operators can only be overloaded for custom types or combinations of standard and custom types.
  • You can only create your own operators from symbols allowed in Swift for operators (+*-/&|^%~!=<>.?).
  • It's advisable not to abuse the creation of new operators to avoid reducing code readability.

Trick question.

Can you overload an operator for standard types, for example, to change the meaning of + for Int?

Answer: No, in Swift you cannot override the global behavior of operators for standard types; you can only extend them for your types or specific combinations. For example:

// Error: overloading for Int will not change existing semantics+ func + (lhs: Int, rhs: Int) -> Int { return lhs - rhs // Will not work: conflict with existing behavior }

Examples of real errors due to misunderstanding the nuances of the topic.


Story

A custom operator ** (exponentiation) was created on the project that mistakenly included the wrong precedence, leading to incorrect calculations for expressions like 2 + 3 ** 2. Result: incorrect results, a difficult-to-debug bug.


Story

In a module with an internal API, == was overloaded for a custom type, but hashing (Hashable) was not implemented, which led to incorrect behavior of Set and Dictionary collections, where instances were considered different despite logical equality.


Story

When creating a custom operator, users forgot to document its meaning. A new developer misunderstood the semantics of the operator and applied it to inappropriate data, resulting in hard-to-trace logical errors in business logic.