0
0
Swiftprogramming~3 mins

Why Base class and subclass in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write shared code once and reuse it everywhere without copying?

The Scenario

Imagine you have to write code for different types of vehicles: cars, bikes, and trucks. You write separate code for each, repeating similar parts like starting the engine or honking the horn.

The Problem

This manual way is slow and boring. If you want to change how all vehicles start, you must update every single code block. It's easy to make mistakes and forget some places.

The Solution

Using a base class and subclasses lets you write shared code once in the base class. Each subclass then adds its own special features. This saves time and keeps your code neat and easy to fix.

Before vs After
Before
func startCar() { print("Engine started") }
func startBike() { print("Engine started") }
func startTruck() { print("Engine started") }
After
class Vehicle {
  func start() { print("Engine started") }
}
class Car: Vehicle {}
class Bike: Vehicle {}
class Truck: Vehicle {}
What It Enables

You can build complex programs with many related parts that share behavior but also have their own unique actions.

Real Life Example

Think of a game where you have different characters: warriors, mages, and archers. They all move and attack, but each in their own way. Base classes and subclasses help organize this easily.

Key Takeaways

Base class holds shared code for many objects.

Subclasses add or change features without repeating code.

This approach saves time and reduces errors.