0
0
Swiftprogramming~5 mins

Reference sharing and side effects in Swift

Choose your learning style9 modes available
Introduction

Reference sharing means two or more variables point to the same data. Side effects happen when changing data through one variable also changes it for others.

When you want multiple parts of your program to work with the same data without copying it.
When you want to update data in one place and have all references see the change.
When you want to avoid using extra memory by not duplicating large data.
When you want to understand why changing one variable affects another unexpectedly.
When debugging bugs caused by shared data changes.
Syntax
Swift
class MyClass {
    var value: Int
    init(value: Int) {
        self.value = value
    }
}

let a = MyClass(value: 10)
let b = a  // b references the same object as a
b.value = 20  // changes value inside the shared object

Classes in Swift are reference types, so variables hold references to the same object.

Changing the object through one variable affects all variables referencing it.

Examples
Both box1 and box2 point to the same Box object. Changing content via box2 changes box1's content too.
Swift
class Box {
    var content: String
    init(content: String) {
        self.content = content
    }
}

let box1 = Box(content: "Apple")
let box2 = box1
box2.content = "Orange"
print(box1.content)  // Output: Orange
Structs are value types. p2 is a copy of p1, so changing p2 does not affect p1.
Swift
struct Point {
    var x: Int
    var y: Int
}

var p1 = Point(x: 1, y: 2)
var p2 = p1
p2.x = 10
print(p1.x)  // Output: 1
Sample Program

counterA and counterB both reference the same Counter object. Changing count via counterB also changes it for counterA.

Swift
class Counter {
    var count: Int
    init(count: Int) {
        self.count = count
    }
}

let counterA = Counter(count: 5)
let counterB = counterA

print("Before change:")
print("counterA.count = \(counterA.count)")
print("counterB.count = \(counterB.count)")

counterB.count += 10

print("After change:")
print("counterA.count = \(counterA.count)")
print("counterB.count = \(counterB.count)")
OutputSuccess
Important Notes

Reference sharing happens only with classes (reference types), not structs or enums (value types).

Be careful: changing shared data can cause unexpected bugs if you forget about other references.

Use 'copy' or create new instances if you want independent data.

Summary

Classes in Swift share references, so variables can point to the same object.

Changing data through one reference affects all others pointing to that object.

Structs do not share references; they copy data instead.