Object
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
===compares identity (the same object),==compares equality viaEquatable.===does not exist for structs.- An object can be mutated through any reference, even when the reference itself is a
let. For a struct,letfreezes the whole value. - An object lives while strong references to it exist (ARC);
deinitruns when the count hits zero. A value dies with its scope.
What else matters
- Messages: in Objective-C a method call is a message resolved at run time. In Swift a call is usually resolved by the compiler (static or vtable); messaging happens only through
@objc dynamic. - Inheritance, encapsulation and polymorphism are properties of classes, not objects; an object merely "carries" its class's behaviour.
ObjectIdentifier(obj)exposes identity as aHashablevalue — handy for dictionary keys and aSetof objects.
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.