Sobes.tech
Junior

What type of collections does Swift use: value types or reference types?

sobes.tech AI

Answer from AI

Swift uses both value types and reference types for collections, but the standard collections (Array, Dictionary, Set) behave as value types.

When copying an instance of Array, Dictionary, or Set, references to the elements are copied, but the collection structure itself is a value. This means that changes in one copy do not affect the other unless the elements themselves are reference types.

Example:

// Array is a value type
var array1 = [1, 2, 3]
var array2 = array1 // Performs a shallow copy

array2[0] = 100 // Changing array2 does not affect array1

print(array1) // Output: [1, 2, 3]
print(array2) // Output: [100, 2, 3]

If the collection's elements are reference types, then copying the collection copies references to the same objects.

class MyClass {
    var value: Int
    init(_ value: Int) { self.value = value }
}

var arrayA = [MyClass(1), MyClass(2)]
var arrayB = arrayA // Copies references to the same MyClass instances

arrayB[0].value = 100 // Changing the property of the object via reference affects both collections

print(arrayA[0].value) // Output: 100
print(arrayB[0].value) // Output: 100

This behavior is optimized with "copy-on-write": the actual copying of collection data occurs only when one of its copies is modified. This improves performance, especially when passing collections to functions.

What type of collections does Swift use: value types… - sobes.tech