0
0
Swiftprogramming~5 mins

Structs are value types (copy on assign) in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Structs are value types (copy on assign)
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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).
How Execution Grows With Input

The copy of the array happens only when the copy is changed, not on assignment.

Input Size (n)Approx. Operations
10Copy about 10 elements
100Copy about 100 elements
1000Copy about 1000 elements

Pattern observation: The cost grows linearly with the size of the array when modified.

Final Time Complexity

Time Complexity: O(n)

This means copying a struct with an array costs time proportional to the array size when you change it.

Common Mistake

[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.

Interview Connect

Understanding how structs copy data helps you explain performance in Swift code clearly and confidently.

Self-Check

"What if the struct contained only simple values instead of an array? How would the time complexity change?"