Structs are value types (copy on assign) in Swift - Time & Space Complexity
When working with structs in Swift, it's important to understand how copying affects performance.
We want to see how the cost changes when structs are assigned or passed around.
Analyze the time complexity of copying a struct with an array property.
struct DataStruct {
var numbers: [Int]
}
let n = 1000
var original = DataStruct(numbers: Array(1...n))
var copy = original // Copy happens here
copy.numbers.append(100)
This code creates a struct holding an array, then copies it and modifies the copy.
Look for operations that repeat or scale with input size.
- Primary operation: Copying the array inside the struct when modified.
- How many times: Happens once at the point of modification (append).
The copy of the array happens only when the copy is changed, not on assignment.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Copy about 10 elements |
| 100 | Copy about 100 elements |
| 1000 | Copy about 1000 elements |
Pattern observation: The cost grows linearly with the size of the array when modified.
Time Complexity: O(n)
This means copying a struct with an array costs time proportional to the array size when you change it.
[X] Wrong: "Assigning a struct is always a cheap operation regardless of size."
[OK] Correct: The actual copy of data happens only when you modify the copy, and that copy cost depends on the data size.
Understanding how structs copy data helps you explain performance in Swift code clearly and confidently.
"What if the struct contained only simple values instead of an array? How would the time complexity change?"