Classes vs Structs
- Swift uses both classes and structs for creating custom data types.
- Classes and structs share common features such as properties, methods, initializers, and access control.
- Classes differ from structs in five key areas.
- Inheritance
- Memberwise initializer generation
- Reference type behavior
- Deinitializers
- Property modification of constant instances.
- Inheritance allows one class to build upon the functionality of another class, with the ability to selectively override methods.
- Swift doesn't automatically generate a memberwise initializer for classes, requiring manual initializer implementation or assigning default property values.
- Copies of a class instance share the same data, so changes made to one copy affect all other copies.
- Deinitializers are special functions executed when the final copy of a class instance is destroyed.
- Modifying properties of a constant class instance is allowed as long as the properties themselves are variables.
- Classes are extensively used in SwiftUI for sharing data across different parts of an app.
class Game {
var score = 0 {
didSet {
print("Score is now \\(score)")
}
}
}
var newGame = Game()
newGame.score += 10 // Score is now 10
Sample code
- Defines a
Bottle
class with a c**apacity**
property and a didSet
property observer.
- The
didSet
observer is triggered whenever the c**apacity**
property changes, printing the updated capacity of the bottle.
class Bottle {
var capacity = 0 {
didSet {
print("Bottle capacity is now \\(capacity) ml")
}
}
}
var waterBottle = Bottle()
waterBottle.capacity += 500 // Bottle capacity is now 500 ml