Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Overload Operators in Swift
Written by Team Kodeco

Operator overloading in Swift allows you to change the behavior of existing operators for your custom types. This can be used to make your code more readable and expressive.

The general syntax for overloading an operator in Swift is as follows:

func operator(lhs: Type, rhs: Type) -> ReturnType {
  // Implementation of operator
}

Where operator is the operator you wish to overload, lhs and rhs are the left-hand side and right-hand side operands respectively, Type and ReturnType are the types of the operands and the return value respectively.

For example, to overload the + operator to add two instances of a custom struct:

struct Vector2D {
  var x: Double
  var y: Double
  static func +(lhs: Vector2D, rhs: Vector2D) -> Vector2D {
    return Vector2D(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
  }
}
let vector1 = Vector2D(x: 1, y: 2)
let vector2 = Vector2D(x: 3, y: 4)
let vector3 = vector1 + vector2
print(vector3) // Vector2D(x: 4.0, y: 6.0)

In this example, we have created a struct Vector2D and overload the + operator using a static function. The function takes two instances of Vector2D as input and return a new instance with the addition of their x and y properties.

© 2024 Kodeco Inc.