DevPrep

All topics › Object-oriented programming (OOP)

Objects and references

Junior

Essence

In classic OOP an "object" almost always means a reference type: a variable stores an address, several variables may point at the same object, and a change through one is visible through the other. In Swift that is only half the story: there are reference types (class, actor, closures) and value types (struct, enum, tuples), and choosing between them is a key design decision.

Example

final class Node { var value: Int; init(_ v: Int) { value = v } }
struct Point { var x: Int }

let n1 = Node(1)
let n2 = n1              // same object, retain count 2
n2.value = 42
print(n1.value)          // 42 — shared state
print(n1 === n2)         // true — identity, not equality

var p1 = Point(x: 1)
var p2 = p1              // independent copy
p2.x = 42
print(p1.x)              // 1

final class Parent { var child: Child? }
final class Child { weak var parent: Parent? }   // breaks the cycle
let parent = Parent()
parent.child = Child()
parent.child?.parent = parent

Reference types

Value types

What the interviewer looks for

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