0
0
Swiftprogramming~3 mins

Why Reference sharing and side effects in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if changing one thing secretly changes another you didn't expect?

The Scenario

Imagine you have a list of friends' names written on a piece of paper. You give this paper to your friend to add more names. Later, you notice the original list has changed without you writing anything new. This surprises you because you thought your list was safe and unchanged.

The Problem

When you manually copy data without understanding how references work, you might accidentally share the same list between different parts of your program. This causes unexpected changes, making your program buggy and hard to fix. Tracking these hidden changes is like chasing shadows.

The Solution

Understanding reference sharing helps you know when different parts of your program are looking at the same data. This awareness lets you control changes carefully, avoiding surprises and making your code more reliable and easier to maintain.

Before vs After
Before
class Person {
  var friends: [String]
  init(friends: [String]) {
    self.friends = friends
  }
}

var list1 = Person(friends: ["Alice", "Bob"])
var list2 = list1
list2.friends.append("Charlie")
print(list1.friends)  // Output: ["Alice", "Bob", "Charlie"]
After
class Person {
  var friends: [String]
  init(friends: [String]) {
    self.friends = friends
  }
}

var list1 = Person(friends: ["Alice", "Bob"])
var list2 = Person(friends: list1.friends)
list2.friends.append("Charlie")
print(list1.friends)  // Output: ["Alice", "Bob"]  // Using copy to avoid side effects
What It Enables

It lets you write programs where data changes happen only when you want, preventing hidden bugs and making your code trustworthy.

Real Life Example

In a drawing app, if two tools share the same shape data by reference, changing the shape in one tool might unexpectedly change it in the other. Understanding reference sharing helps keep each tool's shapes separate unless you want them linked.

Key Takeaways

Reference sharing means multiple parts can see and change the same data.

Without care, this causes hidden side effects and bugs.

Knowing this helps you control when and how data changes happen.