Classes are similar to structs in that they allow you to create new types with properties and methods, but they have five important differences and I’m going to walk you through each of those differences one at a time.
The first difference between classes and structs is that classes never come with a memberwise initializer. This means if you have properties in your class, you must always create your own initializer.
class Dog {
var name: String
var breed: String
init(name: String, breed: String) {
self.name = name
self.breed = breed
}
}
let poppy = Dog(name: "Poppy", breed: "Poodle")
print(poppy)
The second difference between classes and structs is that you can create a class based on an existing class – it inherits all the properties and methods of the original class, and can add its own on top.
This is called class inheritance or subclassing, the class you inherit from is called the “parent” or “super” class, and the new class is called the “child” class.
class Dog {
var name: String
var breed: String
init(name: String, breed: String) {
self.name = name
self.breed = breed
}
}
class Poodle: Dog {
init(name: String) {
super.init(name: name, breed: "Poodle")
}
}
class Dog {
func makeNoise() {
print("Woof!")
}
}
class Poodle: Dog {
override func makeNoise() {
print("Yip!")
}
}
print(Poodle().makeNoise())