0
0
Swiftprogramming~3 mins

Why Structs are value types (copy on assign) in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your data could protect itself from accidental changes every time you share it?

The Scenario

Imagine you have a paper form filled with your details. You want to give a copy to a friend, but you also want to keep your original safe. If you just hand over the original, any changes your friend makes will affect your form too.

The Problem

Manually copying data every time you assign or pass it around is slow and error-prone. You might forget to copy, or accidentally share the original, causing unexpected changes and bugs.

The Solution

Structs in Swift automatically create a fresh copy when you assign or pass them. This means your original data stays safe and unchanged, while others work on their own copies without interference.

Before vs After
Before
struct MyStruct {
    var value: Int
}

var original = MyStruct(value: 0)
var copy = original // both share same data
copy.value = 10 // original also changes
After
struct MyStruct {
    var value: Int
}

var original = MyStruct(value: 0)
var copy = original // copy is a new value
copy.value = 10 // original stays unchanged
What It Enables

This lets you work confidently with data, knowing changes won't sneakily affect other parts of your program.

Real Life Example

Think of a game where each player has their own character stats. Using structs means each player's stats are independent copies, so one player's changes don't mess up another's.

Key Takeaways

Structs automatically copy data on assignment.

This prevents accidental changes to shared data.

It makes your code safer and easier to understand.