Swift - Comparing Instances using Identity Operators

Introduction

To compare two instances of a class to determine if they are the same.

There are two types of comparison that you will perform:

  • Compare whether two variables are pointing to the same instance.
  • Compare whether two instances have the same value.

To illustrate the first, consider the following example.

Suppose you have the following three instances of Point -pt1 , pt2 , and pt3 :

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

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

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                                  
y = 50.0                   

pt1 and pt2 are both pointing to the same instance, while pt3 is pointing to another instance.

To check whether pt1 and pt2 are pointing to the same instance, use the identical to === operator:

if pt1 === pt2 {
    print("pt1 is identical to pt2")
} else {
    print("pt1 is not identical to pt2")
}

The preceding code snippet will output the following:

pt1 is identical to pt2

The next code checks whether pt1 and pt3 are pointing to the same instance:

if pt1 === pt3 {
    print("pt1 is identical to pt3")
} else {
    print("pt1 is not identical to pt3")
}

The preceding code snippet will output the following:

pt1 is not identical to pt3

Besides the identical to === operator, Swift supports the not identical to !== operator.

Related Topic