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.
Reference sharing and side effects in 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.
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
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
counterA and counterB both reference the same Counter object. Changing count via counterB also changes it for counterA.
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)")
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.
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.