Classes vs. Structs in Swift
Classes vs. Structs in Swift
Classes and structs are both ways to create objects in the Swift programming language. The main answer to this interview questions on classes versus structs is that classes are reference types and structs are value types.
Class
So we have car class here let’s create a car. Because this is a class this is a reference type, what that means is that it’s a reference or pointer to specific data so for example if someone steals my car and set it equal to stolen car. Now we have two variables again it’s a reference, they’re both pointing to the same piece of data. So on the stolen car if someone wants to make my car a different color it’s going to affect the original my car.
1 |
|
Classes are reference types and if you create multiple variables of the same class they’re all going to point to the same piece of data and if you change that piece of data on any one of those variables that is going to change that property for all of those variables that are all pointing to that same piece of data.
Struct
Structs are value type types when a value type gets passed around it is copied.
1 |
|
Struct is a value type so it created a copy of my car and assigned it to stolen car.
When to use a class or struct
A benefit of classes is that they have what’s called inheritance. If you don’t need all that inheritance you can just use a struct and that’s why structs are a lot more lightweight and performant and if you’ve written Swift UI you’ll notice a lot of Swift UI is built on structs for that exact reason. A swift UI view is a struct so it can be created and redestroed all the time and it’s not so heavy. So when you need an inheritance or you need a reference type that’s when you go for a class when you don’t need inheritance you want something lightweight and performant then you go with a struct.