DevPrep

All topics › Programming basics

Object

Junior

Essence

An object is an instance of a class living on the heap: it has state (property values), behaviour (methods) and identity — a memory address that distinguishes it from another object holding the same data. In Swift an object in the strict sense is an instance of a class (or actor); an instance of a struct/enum is called a value — it has no identity, only equality.

Object vs value

final class Counter {
    var value = 0
    func increment() { value += 1 }
}

let a = Counter()
let b = a                 // a second reference to the same entity
b.increment()
print(a.value)            // 1
print(a === b)            // true — one identity

struct Point: Equatable { var x = 0 }
let p1 = Point()
var p2 = p1               // an independent copy
p2.x = 5
print(p1 == p2)           // false — values have equality but no identity

What else matters

What the interviewer looks for

Can you explain when identity is needed (a shared mutable resource: a connection, a cache, a controller) and when a value is enough (a data model, a DTO, coordinates). Apple's answer: default to struct, use class when you need identity, inheritance or Objective-C interoperability.

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store