Swift - Comparing Instances using Equivalence Operators

Introduction

To know if two instances are actually the "same"-i.e., if they have the same values.

You need to define that meaning yourself through operator overloading.

The following code snippet includes the definition of the Point class, as well as two operator overloading functions:

class Point {
    var x: Double
    var y: Double
    let width: Int

    init() {
        x = 0.0
        y = 0.0
        width = 2
    }
}

func == (ptA: Point, ptB: Point) -> Bool {
     return (ptA.x == ptB.x) &&  (ptA.y == ptB.y)
}

func != (ptA: Point, ptB: Point) -> Bool {
     return !(ptA == ptB)
}

The two functions are overloading the two operators: equal == and not equal !=

Each function takes two Point instances and returns a Bool value.

Two instances are deemed to be the same if the x and y properties of each instance are equal to the other instance.

You can now use the == operator to test if pt1 and pt3 have the same value:

var pt1 = Point()
pt1.x = 25.0
pt1.y = 50.0
var pt2 = pt1

var pt3 = Point()
pt3.x = 25.0
pt3.y = 50.0

if pt1 == pt3 {
      print("pt1 is same as pt3")
} else {
     print("pt1 is not the same as pt3")
}

The preceding will output the following:

pt1 is same as pt3

You can also use the != operator to compare the two instances:

if pt1 !=  pt3 {
    print("pt1 is not the same as pt3")
} else {
    print("pt1 is same as pt3")
}

Related Topic