Classes vs. Structs in Swift

Classes vs. Structs in Swift

Classes and structs are both ways to model data in Swift. The main distinction is that classes are reference types, while structs are value types.

Class

Here we have a Car class. Because classes are reference types, variables contain references to specific instances. If we assign myCar to stolenCar, both variables point to the same data. Changing stolenCar.color therefore also changes myCar.color.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Car {
var year: Int
var make: String
var color: String
init(year: Int, make: String, color: String) {
self.year = year
self.make = make
self.color = color
}
}

var myCar = Car(year: 2022, make: "Porsche", color: "Grey")
var stolenCar = myCar
stolenCar.color = "Yellow"
print(myCar.color)
//Yellow

Classes are reference types. If multiple variables reference the same instance, changing a property through one variable makes that change visible through every other variable that points to the instance.

Struct

Structs are value types. When a value type is passed around, its value is copied.

1
2
3
4
5
6
7
8
9
10
11
12
struct Car {
var year: Int
var make: String
var color: String

}

var myCar = Car(year: 2022, make: "Porsche", color: "Grey")
var stolenCar = myCar
stolenCar.color = "Yellow"
print(myCar.color)
//Grey

A struct is a value type, so assigning myCar to stolenCar creates a copy. Changing the copy does not affect the original value.

When to use a class or struct

One benefit of classes is inheritance. Use a class when you need inheritance, shared identity, or reference semantics. When you do not need those features, a struct is often the better choice because it provides straightforward value semantics. SwiftUI views are structs and can be created and recreated efficiently as state changes.


Classes vs. Structs in Swift
http://runningcoconut.com/2024/09/04/Classes-vs-Structs-in-Swift/
Author
Huajing Lu
Posted on
September 4, 2024
Licensed under