Reader small image

You're reading from  SwiftUI Essentials – iOS 14 Edition

Product typeBook
Published inMay 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781801813228
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

11. An Introduction to Swift Subclassing and Extensions

In “The Basics of Swift Object-Oriented Programming” we covered the basic concepts of object-oriented programming and worked through an example of creating and working with a new class using Swift. In that example, our new class was not derived from any base class and, as such, did not inherit any traits from a parent or super class. In this chapter we will introduce the concepts of subclassing, inheritance and extensions in Swift.

11.1 Inheritance, Classes and Subclasses

The concept of inheritance brings something of a real-world view to programming. It allows a class to be defined that has a certain set of characteristics (such as methods and properties) and then other classes to be created which are derived from that class. The derived class inherits all of the features of the parent class and typically then adds some features of its own.

By deriving classes we create what is often referred to as a class hierarchy. The class at the top of the hierarchy is known as the base class or root class and the derived classes as subclasses or child classes. Any number of subclasses may be derived from a class. The class from which a subclass is derived is called the parent class or super class.

Classes need not only be derived from a root class. For example, a subclass can also inherit from another subclass with the potential to create large and complex class hierarchies...

11.2 A Swift Inheritance Example

As with most programming concepts, the subject of inheritance in Swift is perhaps best illustrated with an example. In “The Basics of Swift Object-Oriented Programming” we created a class named BankAccount designed to hold a bank account number and corresponding current balance. The BankAccount class contained both properties and instance methods. A simplified declaration for this class is reproduced below:

class BankAccount {

 

    var accountBalance: Float

    var accountNumber: Int

 

    init(number: Int, balance: Float)

    {

        accountNumber = number

        accountBalance = balance

    }

 

    func displayBalance()

    {

    ...

11.3 Extending the Functionality of a Subclass

So far we have been able to create a subclass that contains all the functionality of the parent class. For this exercise to make sense, however, we now need to extend the subclass so that it has the features we need to make it useful for storing savings account information. To do this, we simply add the properties and methods that provide the new functionality, just as we would for any other class we might wish to create:

class SavingsAccount: BankAccount {

 

    var interestRate: Float = 0.0

 

    func calculateInterest() -> Float

    {

        return interestRate * accountBalance

    }

}

11.4 Overriding Inherited Methods

When using inheritance, it is not unusual to find a method in the parent class that almost does what you need, but requires modification to provide the precise functionality you require. That being said, it is also possible you’ll inherit a method with a name that describes exactly what you want to do, but it actually does not come close to doing what you need. One option in this scenario would be to ignore the inherited method and write a new method with an entirely new name. A better option is to override the inherited method and write a new version of it in the subclass.

Before proceeding with an example, there are two rules that must be obeyed when overriding a method. First, the overriding method in the subclass must take exactly the same number and type of parameters as the overridden method in the parent class. Second, the new method must have the same return type as the parent method.

In our BankAccount class we have...

11.5 Initializing the Subclass

As the SavingsAccount class currently stands, it inherits the init initializer method from the parent BankAccount class which was implemented as follows:

init(number: Int, balance: Float)

{

        accountNumber = number

        accountBalance = balance

}

Clearly this method takes the necessary steps to initialize both the account number and balance properties of the class. The SavingsAccount class, however, contains an additional property in the form of the interest rate variable. The SavingsAccount class, therefore, needs its own initializer to ensure that the interestRate property is initialized when instances of the class are created. This method can perform this task and then make a call to the init method of the parent class to complete the initialization of the remaining variables:

class SavingsAccount: BankAccount {

 

   ...

11.6 Using the SavingsAccount Class

Now that we have completed work on our SavingsAccount class, the class can be used in some example code in much the same way as the parent BankAccount class:

let savings1 = SavingsAccount(number: 12311, balance: 600.00,

                                     rate: 0.07)

 

print(savings1.calculateInterest())

savings1.displayBalance()

11.7 Swift Class Extensions

Another way to add new functionality to a Swift class is to use an extension. Extensions can be used to add features such as methods, initializers, computed properties and subscripts to an existing class without the need to create and reference a subclass. This is particularly powerful when using extensions to add functionality to the built-in classes of the Swift language and iOS SDK frameworks.

A class is extended using the following syntax:

extension ClassName {

  // new features here

}

For the purposes of an example, assume that we need to add some additional properties to the standard Double class that will return the value raised to the power 2 and 3. This functionality can be added using the following extension declaration:

extension Double {

 

    var squared: Double {

        return self * self

    }

 

  ...

11.8 Summary

Inheritance extends the concept of object re-use in object-oriented programming by allowing new classes to be derived from existing classes, with those new classes subsequently extended to add new functionality. When an existing class provides some, but not all, of the functionality required by the programmer, inheritance allows that class to be used as the basis for a new subclass. The new subclass will inherit all the capabilities of the parent class, but may then be extended to add the missing functionality.

Swift extensions provide a useful alternative option to adding functionality to existing classes without the need to create a subclass.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
SwiftUI Essentials – iOS 14 Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801813228
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth