Why choose a struct instead of a class in Swift?
Hi everyone! I just started learning Swift and I'm confused. I understand that both structs and classes can have properties and methods. It seems the only difference is that structs are value types and classes are reference types. But in practice, I don't fully understand when to use which.
Here's an example. I'm writing a simple notes app. I created a Note class:
```swift
class Note {
var title: String
var content: String
init(title: String, content: String) {
self.title = title
self.content = content
}
}
var note1 = Note(title: "Shopping", content: "Buy milk")
var note2 = note1
note2.title = "Urgent tasks"
print(note1.title) // Prints "Urgent tasks" — I didn't expect this!
```
I thought th
No answers yet.
Log in to leave an answer