== vs ===

Swift language Junior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Predict the output

What happens?

final class User {
    let id: Int
    init(id: Int) { self.id = id }
}
let a = User(id: 1), b = User(id: 1)
print(a === b)
print(a == b)
Options
Hint 1 of 1

What does == require?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: C It doesn't compile, because User isn't Equatable

Correct. == needs Equatable. === alone would print false.

Why not the others?
  • A false, false. The second line never runs; it doesn't compile.
  • B false, true. Swift doesn't compare class properties automatically.
  • D true, true. These are two different instances.

30-second answer

== checks value equality and requires the type to conform to Equatable. === checks identity: whether two class references point to the same instance. For classes you can use === without Equatable; using == on a class that doesn't conform to Equatable is a compile error.

Practise saying it · 30 s. No recording, just a timer

Explain == vs ===.

Say your answer out loud, then check which of these points you covered:

  • == is Equatable value equality
  • === is reference identity
  • Classes need explicit Equatable

Deep dive

Structs get Equatable synthesized when all stored properties are Equatable.

=== works only with class (AnyObject) references.

Identity matters for caches and delegates; equality matters for data.

ObjectIdentifier(obj) gives a hashable identity.

Common mistakes

  • Expecting == to compare references by default.
  • Implementing == inconsistently with hash.

Senior take & follow-ups

Seniors explain that == is a protocol requirement, not built-in reference equality.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you make a class Equatable?

    Show hint

    Conform and implement ==, usually by an id.

  2. When do you compare identity?

    Show hint

    When you need the same instance, not equal data.

Suggest a fix if something here is wrong or out of date.