Why choose struct instead of class in Swift?
Hello everyone! I just started learning Swift, and I have one question bothering me. I see that Swift has both classes and structs. At first glance, they are very similar: both can have properties, methods, and initializers. But everywhere it says that structs are "value types" and classes are "reference types." I don't fully understand what this means in practice.
I wrote a simple example. I created a `CarClass` class and a `CarStruct` struct with one property `model`. Then I assigned the class instance to a new variable and changed the model in the "copy." The model changed in the original object too! But this didn't happen with the struct. Here's the code:
```swift
class CarClass {
var model = "Tesla"
}
struct CarStruct {
var model = "Tesla"
}
let car1 = CarClass()
No answers yet.
Log in to leave an answer
Blogs
Monorepository with JavaScript: Code Organization and Best Practices