Swift Tutorials: Understanding Base Classes 🎯

beginner
16 min

Swift Tutorials: Understanding Base Classes 🎯

Introduction 📝

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.

What are 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.

Inheritance and Superclass/Subclass Relationship 📝

  • A superclass is a general class that provides a basic structure, which is then specialized by one or more subclasses.
  • A subclass inherits properties and methods from its superclass and can add new properties and methods, or even override existing ones.

Creating a Base Class 🎯

Here's a simple example of creating a base class:

swift
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:).

Subclassing 🎯

Now let's create a subclass, Car, that inherits from the Vehicle base class:

swift
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.

Overriding Methods 🎯

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:

swift
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 💡

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.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

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! 🎯📝✅