0
0
Swiftprogramming~3 mins

Why inheritance is class-only in Swift - The Real Reasons

Choose your learning style9 modes available
The Big Idea

Discover why Swift trusts only classes to carry the power of inheritance and how it keeps your code safe and clean!

The Scenario

Imagine you want to create different types of animals in your app, like dogs and cats, and share some common features like making sounds or moving. Without inheritance, you'd have to copy and paste the same code for each animal type, which quickly becomes messy and hard to manage.

The Problem

Copying code for each type means if you want to change a shared behavior, you must update it everywhere. This is slow and error-prone. Also, without a clear hierarchy, your code becomes confusing and hard to extend.

The Solution

Inheritance lets you create a base class with shared features, and other classes can build on it. Swift limits inheritance to classes because classes support reference behavior and identity, which are essential for inheritance to work correctly and safely.

Before vs After
Before
struct Dog { func sound() { print("Bark") } }
struct Cat { func sound() { print("Meow") } }
After
class Animal { func sound() { print("Some sound") } }
class Dog: Animal { override func sound() { print("Bark") } }
class Cat: Animal { override func sound() { print("Meow") } }
What It Enables

Inheritance in classes allows you to create clear, reusable, and extendable code structures that model real-world relationships easily.

Real Life Example

Think of a vehicle app where you have a base Vehicle class with common features like speed and fuel, and subclasses like Car and Bike that add their own unique behaviors.

Key Takeaways

Inheritance helps share and extend code efficiently.

Swift restricts inheritance to classes for safety and clarity.

This makes your code easier to maintain and grow.