What if your data could protect itself from accidental changes every time you share it?
Why Structs are value types (copy on assign) in Swift? - Purpose & Use Cases
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.
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.
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.
struct MyStruct {
var value: Int
}
var original = MyStruct(value: 0)
var copy = original // both share same data
copy.value = 10 // original also changesstruct MyStruct {
var value: Int
}
var original = MyStruct(value: 0)
var copy = original // copy is a new value
copy.value = 10 // original stays unchangedThis lets you work confidently with data, knowing changes won't sneakily affect other parts of your program.
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.
Structs automatically copy data on assignment.
This prevents accidental changes to shared data.
It makes your code safer and easier to understand.