Ad space (banner)
๐ŸฆSwift Lessons
Lesson 40 / 68

Shallow Copy vs. Deep Copy

In this lesson you will learn the difference between a shallow and a deep copy in Swift, so you can avoid bugs caused by unintentionally shared data. This is for anyone searching for "Swift shallow copy deep copy".

Assigning a Swift struct copies the value itself, but assigning a class instance passes a reference to the same object. That is the shallow-copy situation for classes.

In the sample code, let shallow = original makes shallow point at the same Address instance as original. So setting shallow.city = "Osaka" also changes what original.city prints.

A common stumbling block for beginners is the bug where "I copied it, but the original changed too". Understanding the difference between reference types and value types is important knowledge for working correctly with memory in Swift.

In real-world development, when you want genuinely independent data you have to create a new instance and copy the values across.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)