Swift Inheritance Introduction šŸŽÆ

beginner
7 min

Swift Inheritance Introduction šŸŽÆ

Welcome to the exciting world of Swift Inheritance! Today, we'll explore this powerful feature that enables code reusability and class hierarchy. Let's dive in! 🐟

Understanding Inheritance šŸ“

Inheritance is a mechanism that allows one class (called the subclass or derived class) to acquire the properties and methods of another class (called the superclass or base class). This way, we can create a new class that extends an existing one, saving us from writing redundant code.

šŸ’” Pro Tip: Inheritance is a cornerstone of object-oriented programming (OOP) and makes code more modular, maintainable, and extensible.

Creating a Superclass šŸ“

Let's create a simple superclass called Animal:

swift
class Animal { var name: String var legs: Int init(name: String, legs: Int) { self.name = name self.legs = legs } func walk() { print("\(name) is walking on its \(legs) legs.") } }

In this example, we've created a Animal class with a name and legs property, an initializer to set these properties, and a walk() method.

Inheriting from a Superclass šŸ’”

Now, let's create a subclass called Dog that inherits from Animal:

swift
class Dog: Animal { var breed: String init(name: String, legs: Int, breed: String) { self.breed = breed super.init(name: name, legs: legs) } }

Here, we've defined a Dog class that inherits from Animal. We've added a new breed property and an initializer that takes three arguments. Note that we call super.init() to initialize the properties of the superclass.

Using the Subclass šŸ“

Now, we can create an instance of Dog and call its methods:

swift
let myDog = Dog(name: "Fido", legs: 4, breed: "Labrador") myDog.walk() // "Fido is walking on its 4 legs."

That's it! We've successfully created a subclass that inherits from a superclass in Swift. Let's reinforce our understanding with a quiz:

Quick Quiz
Question 1 of 1

What does inheritance allow a class to do?

Happy coding! šŸš€