Welcome to our Swift Subclassing Rules tutorial! In this comprehensive guide, we'll dive deep into the world of Object-Oriented Programming (OOP) in Swift. By the end, you'll be well-equipped to create your own custom classes and manage inheritance like a pro. 💡
Subclassing is the process of creating a new class that inherits properties and methods from an existing one. This allows us to build more specialized classes by reusing and extending existing functionality.
In Swift, a subclass can only inherit from one superclass. However, a class can adopt multiple protocols, which function similarly to interfaces in other languages.
class Animal {
var name: String
init(name: String) {
self.name = name
}
}
class Dog: Animal {
var breed: String
init(name: String, breed: String) {
self.name = name
self.breed = breed
super.init(name: name) 📝
}
}Here, Dog is a subclass of Animal. When we create a new Dog, it also becomes an Animal thanks to inheritance.
You can modify or replace the behavior of a superclass method by defining a method with the same name and parameters in the subclass. This is called method overriding.
class Animal {
var name: String
func makeNoise() {
print("The \(name) makes a general animal noise.")
}
}
class Dog: Animal {
var breed: String
override func makeNoise() {
print("The \(name) is a \(breed) and barks.")
}
}
let myDog = Dog(name: "Fido", breed: "Labrador")
myDog.makeNoise() 🎯To call a superclass method from a subclass, use the super keyword. This is useful for maintaining consistency and avoiding code duplication.
class Animal {
var name: String
func makeNoise() {
print("The \(name) makes a general animal noise.")
}
}
class Dog: Animal {
var breed: String
override func makeNoise() {
super.makeNoise()
print(" and barks.")
}
}
let myDog = Dog(name: "Fido", breed: "Labrador")
myDog.makeNoise() 🎯What does the `super` keyword do in Swift?
We hope you enjoyed learning about Swift's subclassing rules! Stay tuned for more comprehensive tutorials on CodeYourCraft. Happy coding! 💡