Why classes exist alongside structs in Swift - Performance Analysis
When we look at why Swift has both classes and structs, it helps to think about how their performance changes as we use them more.
We want to understand how the cost of using classes or structs grows when we work with many objects.
Analyze the time complexity of creating and copying structs versus classes.
struct Point {
var x: Int
var y: Int
}
class Circle {
var center: Point
var radius: Int
init(center: Point, radius: Int) {
self.center = center
self.radius = radius
}
}
// Creating many instances
var points = [Point]()
var circles = [Circle]()
for i in 0..
This code creates many Point structs and Circle class instances, showing how they behave when copied or referenced.
Look at what repeats as we create many objects.
- Primary operation: Creating and storing each Point struct and Circle class instance.
- How many times: Exactly n times, once per loop iteration.
As n grows, the number of creations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 creations of structs and classes |
| 100 | 100 creations of structs and classes |
| 1000 | 1000 creations of structs and classes |
Pattern observation: The work grows directly with n, doubling n doubles the work.
Time Complexity: O(n)
This means the time to create and store these objects grows in a straight line with the number of items.
[X] Wrong: "Classes and structs always have the same performance because they both hold data."
[OK] Correct: Structs copy all their data when assigned or passed, which can be costly for large data, while classes use references, so copying is cheaper but managing references adds overhead.
Understanding why Swift has both classes and structs helps you explain design choices clearly and shows you know how performance can change with different data types.
"What if we changed the struct Point to have many properties or nested structs? How would the time complexity of copying change?"
Practice
Solution
Step 1: Understand the difference between classes and structs
Structs are value types, meaning each copy is independent. Classes are reference types, meaning multiple variables can share the same instance.Step 2: Identify why classes are needed
Classes allow shared data through references and support inheritance, which structs do not.Final Answer:
Because classes support shared references and inheritance, while structs do not -> Option CQuick Check:
Classes = shared references + inheritance [OK]
- Thinking structs support inheritance
- Believing classes cannot store data
- Assuming structs are always slower
Solution
Step 1: Recall Swift syntax for class declaration
Classes in Swift are declared using the keywordclassfollowed by the class name and braces.Step 2: Check each option
class MyClass { var name: String } correctly usesclass MyClass { var name: String }. struct MyClass { var name: String } usesstruct, not class. func MyClass() { var name: String } usesfunc, which is incorrect. let MyClass = class { var name: String } uses invalid syntax.Final Answer:
class MyClass { var name: String } -> Option BQuick Check:
Class declaration uses 'class' keyword [OK]
- Using 'struct' instead of 'class'
- Trying to declare class inside a function
- Incorrect syntax with 'let' or 'func'
class Person {
var name: String
init(name: String) { self.name = name }
}
var p1 = Person(name: "Alice")
var p2 = p1
p2.name = "Bob"
print(p1.name)Solution
Step 1: Understand class reference behavior
Classes are reference types, sop1andp2point to the same object.Step 2: Analyze the code changes
Changingp2.nameto "Bob" changes the shared object. Printingp1.nameshows "Bob".Final Answer:
Bob -> Option AQuick Check:
Class variables share references, so name = Bob [OK]
- Thinking p1 and p2 are independent copies
- Expecting 'Alice' as output
- Confusing class with struct behavior
struct Vehicle {
var speed: Int
}
struct Car: Vehicle {
var brand: String
}Solution
Step 1: Understand inheritance rules in Swift
In Swift, only classes support inheritance. Structs cannot inherit from other structs or classes.Step 2: Analyze the code
The code tries to makeCarinherit fromVehicle, both structs, which is invalid.Final Answer:
Structs cannot inherit from other structs or classes -> Option DQuick Check:
Inheritance = classes only, structs no [OK]
- Thinking structs can inherit
- Confusing initializer errors with inheritance
- Misreading colon syntax as error
Solution
Step 1: Identify the need for shared data
The requirement is that multiple parts share and modify the same user profile data, meaning shared references are needed.Step 2: Choose the correct Swift type
Classes are reference types that allow shared references and identity, so changes in one place reflect everywhere. Structs copy data, so changes do not propagate.Final Answer:
Use a class because it allows shared references and identity -> Option AQuick Check:
Shared data needs class reference type [OK]
- Choosing structs for shared mutable data
- Thinking structs support inheritance
- Believing classes cannot store properties
Ready to prove it?
Pass the test and this pattern moves unknown
