Explain the usage of Classes and the Benefits of Inheritance in Swift


Introduction

This article will guide you about the usage of Class and what are the benefits of using inheritance in the Swift language.

In this article, we will cover the following things −

  • What is a class and what is its usage in Swift?

  • What is inheritance and what are its benefits?

What is a Class?

In the Swift language, a class is a representation of properties and methods. We use classes to encapsulate properties and methods into a single entity that has the same characteristics.

We use classes to store information in variables and constants. A class can contain methods to calculate information and return values if required.

For example, we can create a class named Student to store information like name, age, grade, score, school, etc using variables. To manipulate the properties we can define methods.

Benefits of Class

  • It is possible to inherit characteristics from one class to another by using classes.

  • During runtime, typecasting allows users to verify the type of the class.

  • The de-initializer releases memory resources.

Example

In this example, we will create a Student class to store some basic information about a student. We will see how to use these properties by creating a student class.

class Student {
   var name: String
   var grade: Int = 0
   var score: Float = 0.0
   var city: String = ""
   var schoolName: String
   init(name: String, schoolName: String) {
      self.name = name
      self.schoolName = schoolName
   }
   func displayInfo() {
      // display the student information using the required format.
   }
}
let john = Student(name: "John Johnson", schoolName: "Notional School")
print("name: \(john.name)")
print("school name: \(john.schoolName)")

Output

name: John Johnson
school name: Notional School

How can we Store Information in a Class?

Basically, we can store information in a class using properties. Swift's classes can be used to access various types of properties.

Using properties in a class, we can read and write information. We have two types of properties in Swift: stored properties and computed properties.

Swift Language offers Different Types of Properties

  • Stored Properties −These are used to store information permanently. Until that instance is in memory, it will exist in memory. Once you create an instance of a class, it takes up space in memory.

  • Lazy Stored Properties −These are special types of stored properties that will be calculated when accessed for the first time. We used the lazy modifier as a prefix while declaring a lazy property.

  • Computed Properties −For some calculations on the properties of a class, we can use computed properties instead of changing the original values. To achieve this, we can use computed properties that return the calculated value.

Syntax

Syntax to perform actions inside a class

Using methods, we can perform different actions inside a class.

func greeting(_ name: String) {
   print("Good morning, \(name)")
}

What is Inheritance?

Inheritance is a way to adapt the characteristics and methods of one class to another class. By inheritance, we can extend the functionalities of an existing type by adding supplementary characteristics to another type.

When we inherit a class (for eg Class B) from another class (for eg Class A), Class B is called a subclass and Class A is called a superclass.

Benefits of Using Inheritance

There are some benefits to using inheritance in the Swift language. There are the following −

  • Reduce code redundancy.

  • Provides better code reusability.

  • Parent and child classes are easy to maintain while writing code.

  • We can add extra functionality to a subclass by overriding the existing functionality of the parent class.

Example

In the below example, we will create a superclass and some subclasses by inheriting them from the superclass. Let's see how superclasses can be beneficial for us while writing code.

import Foundation
// super class
class Person {
   var name: String
   var address: String
   var age: Int
   init(name: String, address: String, age: Int) {
      self.name = name
      self.address = address
      self.age = age
   }
   func isYoung() -> Bool {
      age >= 18
   }
}
// sub class
class Student: Person {
   var collegeName: String
   var grade: Int
   init(collegeName: String, grade: Int, name: String, address: String, age: Int) {
      self.collegeName = collegeName
      self.grade = grade
      super.init(name: name, address: address, age: age)
   }
   func checkAgeEligibility() {
      if self.isYoung() {
         print("\(self.name) is eligible to take admission.")
      } else {
         print("\(self.name) is not eligible to take admission.")
      }
   }
}
// sub class
class Voter: Person {
   var isPreviouslyCasted: Bool = false
   func eligibleToVote() {
      if self.isYoung() && isPreviouslyCasted {
         print("\(self.name) is eligible to cast vote.")
      } else {
         print("\(self.name) is not eligible to cast vote.")
      }
   }
}
let student = Student(collegeName: "Primary School", grade: 11, name: "Amit Bhalla", address: "New Delhi", age: 13)
student.checkAgeEligibility()
let voter = Voter(name: "Sunil Chandra", address: "Bangalore", age: 21)
voter.eligibleToVote()

Output

Amit Bhalla is not eligible to take admission.
Sunil Chandra is not eligible to cast vote.

Explanation

In the above example, we created a class called Person with the method isYoung() to check the eligibility of the person.

The Student and Voter classes are now inherited from the Person class, with the addition of methods associated with sub-classes.

The superclass has a method that is accessible to all subclasses. So we can take advantage of the superclass functionality.

Conclusion

Inheritance is the most important concept in Swift language to write the core in proper hierarchy. Always, try to define superclasses to make common things separate.

Updated on: 21-Dec-2022

238 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements