Discover why Swift trusts only classes to carry the power of inheritance and how it keeps your code safe and clean!
Why inheritance is class-only in Swift - The Real Reasons
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.
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.
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.
struct Dog { func sound() { print("Bark") } }
struct Cat { func sound() { print("Meow") } }class Animal { func sound() { print("Some sound") } } class Dog: Animal { override func sound() { print("Bark") } } class Cat: Animal { override func sound() { print("Meow") } }
Inheritance in classes allows you to create clear, reusable, and extendable code structures that model real-world relationships easily.
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.
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.