A class in Swift, like classes in other programming languages, serves as a blueprint for creating objects that encapsulate data and behaviour. In Swift, you will see both classes and structs. This post will primarily focus on classes, although I will mention structs throughout to highlight some of the differences.
Classes are reference types, meaning that if you instantiate it, and then make a copy of it, any changes to either copy will be reflected in the other copy.
class Car {
var model: String
init(model: String) {
self.model = model
}
}
let car1 = Car(model: "Ferrari")
let car2 = car1
car2.model = "Lamborghini"
print(car1.model)
Although we changed car2’s model, because car2 is a copy of car1, and that it copies by reference, any changes to car2 here will also be changing car1.
[Read more…]