An Introduction to Swift Inheritance
Previous | Table of Contents | Next |
The Basics of Object Oriented Programming in Swift | Working with Array and Dictionary Collections in Swift |
Learn SwiftUI and take your iOS Development to the Next Level |
In The Basics of Object Oriented Programming in Swift 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 provide an introduction to the concepts of subclassing and inheritance in Swift.
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.
In Swift a subclass can only be derived from a single direct parent class. This is a concept referred to as single inheritance.
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 Object Oriented Programming in Swift 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() { println("Number \(accountNumber)") println("Current balance is \(accountBalance)") } }
Learn SwiftUI and take your iOS Development to the Next Level |
To create a subclass of BankAccount that we will call SavingsAccount, we simply declare the new class, this time specifying BankAccount as the parent class:
class SavingsAccount: BankAccount { }
Note that although we have yet to add any instance variables or methods, the class has actually inherited all the methods and properties of the parent BankAccount class. We could, therefore, create an instance of the SavingsAccount class and set variables and call methods in exactly the same way we did with the BankAccount class in previous examples. That said, we haven't really achieved anything unless we actually take steps to extend the class.
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. In order 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 func calculateInterest() -> Float { return interestRate * accountBalance } }
Learn SwiftUI and take your iOS Development to the Next Level |
Overriding Inherited Methods
Before proceeding with an example, there are two rules that must be obeyed when overriding a method. Firstly, the overriding method in the subclass must take exactly the same number and type of parameters as the overridden method in the parent class. Secondly, the new method must have the same return type as the parent method.
In our BankAccount class we have a method named displayBalance that displays the bank account number and current balance held by an instance of the class. In our SavingsAccount subclass we might also want to output the current interest rate assigned to the account. To achieve this, we simply declare a new version of the displayBalance method in our SavingsAccount subclass, prefixed with the override keyword:
class SavingsAccount: BankAccount { var interestRate: Float func calculateInterest() -> Float { return interestRate * accountBalance } override func displayBalance() { println("Number \(accountNumber)") println("Current balance is \(accountBalance)") println("Prevailing interest rate is \(interestRate)") } }
It is also possible to make a call to the overridden method in the super class from within a subclass. The displayBalance method of the super class could, for example, be called to display the account number and balance, before the interest rate is displayed, thereby eliminating further code duplication:
override func displayBalance() { super.displayBalance() println("Prevailing interest rate is \(interestRate)") }
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 }
Learn SwiftUI and take your iOS Development to the Next Level |
class SavingsAccount: BankAccount { var interestRate: Float init(number: Int, balance: Float, rate: Float) { interestRate = rate super.init(number: number, balance: balance) } . . . }
Note that to avoid potential initialization problems, the init method of the superclass must always be called after the initialization tasks for the subclass have been completed.
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) println(savings1.calculateInterest()) savings1.displayBalance()
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.
Learn SwiftUI and take your iOS Development to the Next Level |
Previous | Table of Contents | Next |
The Basics of Object Oriented Programming in Swift | Working with Array and Dictionary Collections in Swift |