Classes vs Structs

  1. Swift uses both classes and structs for creating custom data types.
  2. Classes and structs share common features such as properties, methods, initializers, and access control.
  3. Classes differ from structs in five key areas.
    1. Inheritance
    2. Memberwise initializer generation
    3. Reference type behavior
    4. Deinitializers
    5. Property modification of constant instances.
  4. Inheritance allows one class to build upon the functionality of another class, with the ability to selectively override methods.
  5. Swift doesn't automatically generate a memberwise initializer for classes, requiring manual initializer implementation or assigning default property values.
  6. Copies of a class instance share the same data, so changes made to one copy affect all other copies.
  7. Deinitializers are special functions executed when the final copy of a class instance is destroyed.
  8. Modifying properties of a constant class instance is allowed as long as the properties themselves are variables.
  9. 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

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