Education
Software Development Executive - II
Last updated on Nov 28, 2024
Last updated on Nov 28, 2024
Creating a class and subclass in Swift is a foundational concept in object-oriented programming (OOP) that allows you to organize code, reuse methods and properties, and establish clear "is-a" relationships between types. Swift, a modern language, offers a streamlined approach to class inheritance, enabling you to create and work with classes easily.
In this blog, you’ll learn how to define a class and create a subclass, exploring various important concepts such as inheritance, property overriding, instance methods, and much more.
In Swift, a class is a blueprint for creating objects that encapsulate properties and methods. Each class defines an object’s data (properties) and behavior (methods). Classes are essential in object-oriented programming (OOP) because they enable you to create multiple instances with common characteristics. Swift classes support a single inheritance model, meaning each derived class can inherit methods and properties from only one superclass.
You start defining a class in Swift using the class keyword. Here’s a simple example of an existing class named Vehicle, often referred to as the vehicle class:
1class Vehicle { 2 var make: String 3 var model: String 4 var year: Int 5 6 init(make: String, model: String, year: Int) { 7 self.make = make 8 self.model = model 9 self.year = year 10 } 11 12 func startEngine() { 13 print("Engine started.") 14 } 15}
In the class Vehicle example above, we have created a Vehicle class with an instance property for make, model, and year, along with an instance method called startEngine. This class defines the properties and methods that every Vehicle instance will have.
In Swift, a subclass inherits properties and methods from its parent class (or base class). This subclass relationship allows you to reuse code while extending the base functionality or providing your custom implementation of existing methods.
Let’s create a car class that inherits from the vehicle class. This subclass, named Car, will represent a more specific type of vehicle. We use the colon syntax to define that the class Car inherits from class Vehicle:
1class Car: Vehicle { 2 var isElectric: Bool 3 4 init(make: String, model: String, year: Int, isElectric: Bool) { 5 self.isElectric = isElectric 6 super.init(make: make, model: model, year: year) 7 } 8 9 override func startEngine() { 10 if isElectric { 11 print("Silently starting electric motor.") 12 } else { 13 super.startEngine() 14 } 15 } 16}
In the above code, Car inherits all properties and methods from Vehicle (our base class). It adds its instance property, isElectric, and also provides a custom implementation of startEngine. Here, the override keyword lets Swift know that startEngine in Car is meant to replace the startEngine function in Vehicle. This is an example of method overriding.
Using the override keyword in Swift is essential to ensure that the subclass’s methods genuinely replace those in the parent class. If you forget to include the override keyword, Swift will throw an error, alerting you to a potential issue. This ensures that each overridden method is explicitly intended as a replacement for the superclass method.
Subclasses can add their own properties or modify inherited ones. Swift also allows for property overriding using property observers, which allow a child class to react when a property’s value changes. Here’s an example of using a property observer in our Car class:
1class Car: Vehicle { 2 var isElectric: Bool { 3 didSet { 4 print("Electric status changed to \(isElectric)") 5 } 6 } 7 8 init(make: String, model: String, year: Int, isElectric: Bool) { 9 self.isElectric = isElectric 10 super.init(make: make, model: model, year: year) 11 } 12}
In this derived class, we add a didSet property observer to isElectric so that whenever the previous value changes, we get a notification.
Swift inheritance supports using the super keyword to access methods, properties, and initializers from a parent class. In the Car class, we used super.startEngine() to call the original implementation of startEngine from the vehicle class.
The super keyword is also necessary when calling an initializer of the base class in a new class initializer:
1init(make: String, model: String, year: Int, isElectric: Bool) { 2 self.isElectric = isElectric 3 super.init(make: make, model: model, year: year) 4}
In the code above, super.init initializes the properties of the base class, allowing the Car initializer to function correctly. Swift’s single inheritance model ensures that each subclass inherits only from a single parent class.
Swift supports type properties and type methods that are tied to the class itself rather than to an instance. You define these with the static keyword or class keyword in Swift.
1class Vehicle { 2 static var vehicleCount = 0 3 4 init() { 5 Vehicle.vehicleCount += 1 6 } 7 8 class func printVehicleCount() { 9 print("Total vehicles: \(vehicleCount)") 10 } 11}
In the class vehicle example, vehicleCount is a type property, and printVehicleCount is a type method. Every time a new instance of Vehicle or its subclass is created, vehicleCount increases, allowing us to track the total number of Vehicle objects.
Swift allows you to mark a class as final, preventing it from being subclassed. This is useful when you want to avoid modification of a class's structure. Similarly, final class func marks a method as final:
1final class Vehicle { 2 final class func description() -> String { 3 return "This is a vehicle." 4 } 5}
Using the final class keyword ensures no child class can override description.
In this article, we explored how to create a Swift subclass. By understanding class inheritance in Swift, you can efficiently structure your code, reuse properties and methods from a base class, and tailor your Swift subclass with custom functionality. We also covered essential concepts like method overriding, the super keyword, and property observers. Mastering these fundamentals will enable you to create flexible, reusable, and well-organized code, unlocking the full potential of Swift’s object-oriented programming capabilities.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.