Comparing structs vs classes decision in Swift - Performance Comparison
When choosing between structs and classes in Swift, it's important to understand how their operations grow as your data size increases.
We want to see how the time cost changes when working with many instances of each type.
Analyze the time complexity of creating and copying structs versus classes.
struct PointStruct {
var x: Int
var y: Int
}
class PointClass {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
// Creating and copying 1000 instances
var structPoints = [PointStruct]()
var classPoints = [PointClass]()
for i in 0..<1000 {
structPoints.append(PointStruct(x: i, y: i))
classPoints.append(PointClass(x: i, y: i))
}
// Copying struct array
let copiedStructPoints = structPoints
// Copying class array
let copiedClassPoints = classPoints
This code creates arrays of structs and classes, then copies the arrays to compare how copying behaves.
Look for loops and copying actions that repeat work.
- Primary operation: Loop creating 1000 instances of structs and classes.
- How many times: 1000 times for creation; copying arrays happens once but behaves differently.
Creating instances grows linearly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 creations |
| 100 | 100 creations |
| 1000 | 1000 creations |
Copying struct arrays duplicates all data, so operations grow with n. Copying class arrays only copies references, so it stays almost constant.
Time Complexity: O(n)
This means the time to create or copy grows directly with the number of items.
[X] Wrong: "Copying a class array duplicates all objects like structs."
[OK] Correct: Copying a class array only copies references, not the objects themselves, so it is much faster than copying structs.
Understanding how structs and classes behave with copying helps you explain performance choices clearly and confidently in real projects.
What if we changed the struct to contain a large array? How would copying the struct array affect time complexity?
Practice
struct instead of a class in Swift?Solution
Step 1: Understand struct behavior
Structs are value types, meaning they are copied when assigned or passed around.Step 2: Compare with class behavior
Classes are reference types, shared by multiple references and support inheritance.Final Answer:
Usestructfor simple data that should be copied when assigned or passed. -> Option CQuick Check:
Structs = copied data [OK]
- Confusing structs with classes as reference types
- Thinking structs support inheritance
- Using structs for shared mutable state
struct in Swift?Solution
Step 1: Recall struct declaration syntax
In Swift, structs are declared with the keywordstructfollowed by the name and braces.Step 2: Check each option
struct Person { var name: String }is correct. Usingclassis incorrect for structs. Structs cannot inherit fromClass, and classes cannot inherit fromstruct.Final Answer:
struct Person { var name: String } -> Option BQuick Check:
Struct declaration =struct Name { }[OK]
- Using 'class' keyword to declare a struct
- Trying to inherit from a class in a struct
- Mixing struct and class syntax
struct Point {
var x: Int
var y: Int
}
var p1 = Point(x: 1, y: 2)
var p2 = p1
p2.x = 10
print(p1.x)What is the output?
Solution
Step 1: Understand struct copying behavior
Assigningp1top2copies the data becausePointis a struct (value type).Step 2: Analyze mutation effect
Changingp2.xto 10 does not affectp1.x, which remains 1.Final Answer:
1 -> Option AQuick Check:
Struct copy means original unchanged = 1 [OK]
- Assuming p1.x changes when p2.x changes
- Confusing structs with classes (reference types)
- Expecting runtime error on mutation
class Counter {
var count = 0
}
var c1 = Counter()
var c2 = c1
c2.count = 5
print(c1.count)But the output is not as expected. What is the problem?
Solution
Step 1: Identify class reference behavior
Classes are reference types, soc1andc2point to the same object.Step 2: Understand shared mutation
Changingc2.countto 5 changes the shared instance, soc1.countalso becomes 5.Final Answer:
Counter is a class, so c1 and c2 share the same instance -> Option AQuick Check:
Classes share references = shared data [OK]
- Thinking classes copy on assignment
- Expecting structs to share data
- Believing protocols affect sharing automatically
Options:
A) Use a struct because it copies data and avoids bugs.B) Use a class because it allows shared mutable state with identity.C) Use a struct with inheritance to share state.D) Use a class but avoid mutability to keep data safe.Solution
Step 1: Analyze requirements for shared mutable state
The session data must be shared and mutable across multiple parts, requiring a single shared instance.Step 2: Choose between struct and class
Structs copy data, so changes in one copy won't reflect elsewhere. Classes share references and support identity, fitting the need.Step 3: Evaluate other options
Structs do not support inheritance, so Use a struct with inheritance to share state. is invalid. Avoiding mutability in classes (Use a class but avoid mutability to keep data safe.) contradicts the requirement for mutable shared state.Final Answer:
Use a class because it allows shared mutable state with identity. -> Option DQuick Check:
Shared mutable state = class [OK]
- Choosing struct for shared mutable state
- Thinking structs support inheritance
- Avoiding mutability in classes when needed
Ready to prove it?
Pass the test and this pattern moves unknown
