Search⌘ K

Swift Object-Oriented Programming Overview

Explore the basics of object-oriented programming (OOP) in Swift, focusing on class structures, data encapsulation, instance and type methods, and initialization. This lesson guides you through creating and managing class instances with practical examples like a BankAccount class, preparing you to apply OOP principles in Swift app development.

Swift provides extensive support for developing object-oriented applications. The subject area of object-oriented programming is, however, large. It is not an exaggeration to state that entire books have been dedicated to the subject. As such, a detailed overview of object-oriented software development is beyond the scope of this course. Instead, we will introduce the basic concepts involved in object-oriented programming and then we will move on to explaining the concept as it relates to Swift application development.

What is an instance?

Objects (also referred to as class instances) are self-contained modules of functionality that can be easily used and reused as the building blocks for a software application.

Instances consist of data variables (called properties) and functions (called methods). These can be accessed and called on the instance to perform tasks and are collectively referred to as class members.

What is a class?

Much likes a blueprint or architect’s drawing defines what an item or a building will look like once it has been constructed, a class defines what an instance will look like when it is created. It defines, for example, what the methods will do and what the properties will be.

Declaring a Swift class

Before an instance can be created, we first need to define the class “blueprint” for the instance. In this lesson, we will create a bank account class to demonstrate the basic concepts of Swift object-oriented programming.

When declaring a new Swift class, we specify an optional parent class from which the new class is derived and also define the properties and methods that the class will contain. The basic syntax for a new class is as follows:

class NewClassName: ParentClass {
   // Properties
   // Instance Methods
   // Type methods
}

The Properties section of the declaration defines the variables and constants that are to be contained within the class. These are declared in the same way that any other variable or constant would be declared in Swift.

The Instance methods and Type methods sections define the methods that are available to be called on the class and instances of the class. These are essentially functions ...