Welcome to our deep dive into Swift's Base Classes! This lesson is perfect for beginners and intermediates who want to master the foundations of object-oriented programming in Swift. Let's embark on a journey to discover the power of inheritance and polymorphism through base classes.
In Swift, a base class is a generalized class that serves as a template for creating other, more specific classes. A base class can have properties and methods, which can then be inherited by its subclasses. This relationship is known as inheritance.
Here's a simple example of creating a base class:
class Vehicle {
var currentSpeed: Int
init(speed: Int) {
self.currentSpeed = speed
}
func increaseSpeed(by increment: Int) {
self.currentSpeed += increment
print("Increased speed by \(increment). Current speed is \(self.currentSpeed)")
}
}In this example, Vehicle is a base class with a property currentSpeed and a method increaseSpeed(by:).
Now let's create a subclass, Car, that inherits from the Vehicle base class:
class Car: Vehicle {
var numberOfDoors: Int
override init(speed: Int, numberOfDoors: Int) {
self.numberOfDoors = numberOfDoors
super.init(speed: speed)
}
}In this example, Car is a subclass of Vehicle. It inherits the currentSpeed property and the increaseSpeed(by:) method from Vehicle, and also adds a new property numberOfDoors.
Sometimes, you might want to change the behavior of a method inherited from the superclass. This is done by overriding the method in the subclass:
class ElectricCar: Car {
override func increaseSpeed(by increment: Int) {
super.increaseSpeed(by: increment)
print("This is an electric car. Accelerating silently.")
}
}In this example, ElectricCar is a subclass of Car. It overrides the increaseSpeed(by:) method to add a custom message.
Polymorphism is the ability of an object to take on many forms. In Swift, this is achieved through inheritance and method overriding. It allows us to write code that works with a general base class but can interact with specific subclasses.
What is the purpose of a base class in Swift?
Stay tuned for more Swift tutorials, where we'll explore advanced topics and real-world applications! 🎯📝✅