What if changing one thing secretly changes another you didn't expect?
Why Reference sharing and side effects in Swift? - Purpose & Use Cases
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.
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.
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.
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"]
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
It lets you write programs where data changes happen only when you want, preventing hidden bugs and making your code trustworthy.
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.
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.