Swift - Operator Overloading and Custom Operators

Introduction

An operator is a function that takes one or two values and returns a value.

Operators can be overloaded.

For example, you could change how the + function works for Int like this:

Demo

extension Int { 
    static func + (left: Int, right: Int) -> Int { 
        return left * right 
    } /* w ww. j a v  a 2  s. c  o m*/
} 

print(4 + 2)

Result

Swift can define new operators and overload existing ones for your types.

For example, imagine you have an object called Vector2D, which stores two floating-point numbers:

class Vector2D { 
    var x  : Float = 0.0 
    var y  : Float = 0.0 

    init (x  : Float, y: Float) { 
        self.x = x 
        self.y = y 
    } 
} 

To add instances of this type of object together using the + operator, implement the + function:

func +(left  : Vector2D, right: Vector2D) -> Vector2D { 
    let result = Vector2D(x: left.x + right.x, y: left.y + right.y) 

    return result 
} 
let first = Vector2D(x: 2, y: 2) 
let second = Vector2D(x: 4, y: 1) 
let result = first + second 

Related Topics