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