0
0
Swiftprogramming~5 mins

Why collections are value types in Swift

Choose your learning style9 modes available
Introduction

Collections in Swift are value types to keep your data safe and predictable. When you change a collection, it doesn't affect others that share it.

When you want to make sure changing one list doesn't change another by accident.
When you want simple and clear data flow in your app.
When you want to avoid bugs caused by shared data changes.
When you want your code to be easier to understand and maintain.
Syntax
Swift
var numbers = [1, 2, 3]
var moreNumbers = numbers
moreNumbers.append(4)

Assigning one collection to another copies the data, not just the reference.

Changing one collection does not change the other.

Examples
Adding "Cherry" to basket does not change fruits because they are separate copies.
Swift
var fruits = ["Apple", "Banana"]
var basket = fruits
basket.append("Cherry")
print(fruits)
print(basket)
Removing an item from setB does not affect setA because sets are value types.
Swift
var setA: Set<Int> = [1, 2, 3]
var setB = setA
setB.remove(2)
print(setA)
print(setB)
Sample Program

This program shows that changing copiedArray does not change originalArray because arrays are value types.

Swift
var originalArray = [10, 20, 30]
var copiedArray = originalArray
copiedArray.append(40)
print("Original:", originalArray)
print("Copied:", copiedArray)
OutputSuccess
Important Notes

Value types help avoid unexpected changes when multiple parts of your code use the same data.

Swift uses a technique called copy-on-write to make copying efficient until you change the data.

Summary

Collections are value types to keep data safe and predictable.

Copying a collection creates a new, independent copy.

This helps prevent bugs from shared data changes.