Fix: Unexpected Class Comparison Results with == and === in Swift

Fix: Unexpected Class Comparison Results with == and === in Swift

Written by

in

Quick answer: Use == to compare values (requires Equatable conformance) and === to check if two references point to the exact same class instance. Classes are reference types, so == and === give different results unless you compare the same instance.

Why this happens

Swift classes are reference types. When you assign a class instance to multiple variables, each variable holds a reference to the same heap object. This creates two distinct comparison scenarios:

  • Value equality (==): Are the contents of the two instances equivalent? This requires your type to conform to Equatable and implement static func ==.
  • Reference identity (===): Do the two variables point to the exact same instance in memory? This is built into the language and works on any class type without extra code.

Confusion arises because structs and enums (value types) only have ==. With classes, both operators exist and return different results for distinct instances that happen to hold equal data.

How to fix it

1. Implement Equatable for value comparisons

If you want person1 == person2 to return true when two Person instances have the same SSN, conform to Equatable and define what “equal” means for your domain.

class Person: Equatable {
    let ssn: Int
    let name: String

    init(ssn: Int, name: String) {
        self.ssn = ssn
        self.name = name
    }

    static func == (lhs: Person, rhs: Person) -> Bool {
        lhs.ssn == rhs.ssn
    }
}

let person1 = Person(ssn: 5, name: "Bob")
let person2 = Person(ssn: 5, name: "Bob")

person1 == person2   // true  (same SSN)
person1 === person2  // false (different heap objects)

Key point: Only compare the fields that define identity (here ssn). Skip mutable or derived properties.

2. Use === when you need instance identity

Use the identity operator when the logic depends on object uniqueness, not data equivalence. Common cases:

  • Checking if a delegate is the same object you assigned earlier
  • Verifying that a cached instance is reused
  • Removing a specific observer from a notification center
class ViewController: UIViewController {
    var dataProvider: DataProvider?

    func setProvider(_ provider: DataProvider) {
        // Only replace if it's a *different* instance
        guard dataProvider !== provider else { return }
        dataProvider = provider
    }
}

3. Avoid accidental reference sharing

If you mutate a class instance, every reference sees the change. When you need independent copies, implement a copy() method or use a value type (struct) instead.

class Settings {
    var theme: String = "light"
    func copy() -> Settings {
        let s = Settings()
        s.theme = theme
        return s
    }
}

let original = Settings()
let duplicate = original.copy()
original.theme = "dark"

original === duplicate  // false
original == duplicate   // false (unless you add Equatable)

How to prevent it

  • Default to structs for data models; they only have value semantics and avoid this confusion entirely.
  • Implement Equatable deliberately — only when “same data” has a clear, stable meaning.
  • Use === explicitly for identity checks; don’t rely on == for reference comparison.
  • Document the equality contract in your type’s header comment so callers know what == compares.
  • Prefer Identifiable + id for SwiftUI lists and diffing; it separates identity from equality cleanly.

FAQ

### Does === work on structs or enums?

No. === and !== are only defined for class types (and class-bound protocols). Value types are always compared by value with ==.

### Can I overload === for my own types?

No. The identity operators are built into the compiler and cannot be overloaded. They always compare raw object references.

### Why does == compile for some classes without Equatable?

Swift synthesizes == for classes that inherit from NSObject (via isEqual:) or when the compiler can infer a tuple comparison for @objc members. For pure Swift classes, you must conform to Equatable explicitly.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.