Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources
Inheritance in Swift

Inheritance in Swift

What is Inheritance?

Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and methods from another class. In Swift, inheritance enables the creation of new classes based on existing ones, promoting code reuse and organization.

Base Class and Subclass

A base class is the class from which other classes inherit. A subclass is a class that inherits from another class (the base class). The subclass can override methods or properties of the base class to provide specific implementations.

Defining a Base Class

To define a base class in Swift, you use the class keyword followed by the class name. Here’s an example of a base class called Animal:

class Animal {
  var name: String
  init(name: String) {
    self.name = name
  }
  func makeSound() {
    print("Some sound")
  }
}

Creating a Subclass

To create a subclass, you specify the base class after the class name using a colon. Here’s how you can create a subclass called Dog that inherits from Animal:

class Dog: Animal {
  override func makeSound() {
    print("Bark")
  }
}

Using Inheritance

Once the subclass is created, you can create instances of the subclass and use the methods and properties inherited from the base class:

let myDog = Dog(name: "Buddy")
myDog.makeSound() // Output: Bark

Overriding Properties

In addition to methods, you can also override properties in a subclass. Here’s an example where we override a property:

class Cat: Animal {
  override var name: String {
    return "Cat: \(super.name)"
  }
}

Final Classes

If you want to prevent a class from being subclassed, you can mark it as final. Here’s how:

final class Bird: Animal {
  func fly() {
    print("Flying")
  }
}

Conclusion

Inheritance is a powerful feature in Swift that allows developers to create a hierarchy of classes, promoting code reuse and organization. By understanding how to create base classes and subclasses, override methods and properties, and control subclassing with final, you can write more efficient and maintainable code.