Swift Classes and Objects

Swift is also an object-oriented programming language. And, like other oop languages, it also supports the concept of objects and classes.

An object is simply a collection of data (variables) and methods (functions). Similarly, a class is a blueprint for that object.

Before we learn about objects, let's first know about classes in Swift.


Swift Classes

A class is considered as a blueprint of objects. We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.

Since many houses can be made from the same description, we can create many objects from a class.


Define Swift Class

We use the class keyword to create a class in Swift. For example,

class ClassName {
  // class definition 
}

Here, we have created a class named ClassName.

Let's see an example,

class Bike {

  var name = ""
  var gear = 0
}

Here,

  • Bike - the name of the class
  • name/gear - variables inside the class with default values "" and 0 respectively.

Note: The variables and constants inside a class are called properties.


Swift Objects

An object is called an instance of a class. For example, suppose Bike is a class then we can create objects like bike1, bike2, etc from the class.

Here's the syntax to create an object.

var objectName = ClassName()

Let's see an example,

// create class
class Bike {

  var name = ""
  var gears = 0
}

// create object of class
var bike1 = Bike()

Here, bike1 is the object of the class. Now, we can use this object to access the class properties.


Access Class Property using Objects

We use the . notation to access the properties of a class. For example,

// modify the name property
bike1.name = "Mountain Bike"

// access the gear property
bike1.gears

Here, we have used bike1.name and bike.gears to change and access the value of name and gears property respectively.


Example: Swift Class and Objects

// define a class
class Bicycle {

// define two properties
var name = ""
var gears = 0
}

// create instance of Person
var bike1 = Bicycle()

// access properties and assign new values
bike1.gears = 11
bike1.name = "Mountain Bike"

print("Name: \(bike1.name), Gears: \( bike1.gears) ")

Output

Name: Mountain Bike, Gears: 11

In the above example, we have defined the class named Bike with two properties: name and gears.

We have also created an object bike1 of the class Bike.

Finally, we have accessed and modified the properties of an object using . notation.


Create Multiple Objects of Class

We can also create multiple objects from a single class. For example,

// define a class
class Employee {

// define a property
var employeeID = 0
}

// create two objects of the Employee class
var employee1 = Employee()
var employee2 = Employee()

// access property using employee1
employee1.employeeID = 1001
print("Employee ID: \(employee1.employeeID)")

// access properties using employee2
employee2.employeeID = 1002
print("Employee ID: \(employee2.employeeID)")

Output

Employee ID: 1001
Employee ID: 1002

In the above example, we have created two objects employee1 and employee2 of the Employee class

Note: We can create as many instances of the structure as we want.


Function Inside Swift Class

We can also define a function inside a Swift class. A Swift Function defined inside a class is called a method.

Let's see an example,

// create a class
class Room {

  var length = 0.0
  var breadth = 0.0

  // method to calculate area
  func calculateArea() {
    print("Area of Room =", length * breadth)
  }
}

  // create object of Room class
  var studyRoom = Room()

  // assign values to all the properties 
  studyRoom.length = 42.5
  studyRoom.breadth = 30.8

  // access method inside class
  studyRoom.calculateArea()

Output

Area of Room = 1309.0

In the above example, we have created a class named Room with:

  • Properties: length and breadth
  • Method: calculateArea()

Here, we have created an object named studyRoom from the Room class. We then used the object to assign values to properties: length and breadth.

Notice that we have also used the object to call the method inside the class

room1.calculateArea()

Here, we have used the . notation to call the method. Finally, the statement inside the method is executed.


Swift Initializer

Earlier we assigned a default value to a class property.

class Bike {
  
  var name = ""
}
...

// create object
var bike = Bike()

However, we can also initialize values using the initializer. For example,

class Bike {
  
  var name: String

  init(name: String){
  self.name = name
  }
}

Here, init() is the initializer that is used to assign the value of the name variable. We have used the self.name to refer to the name property of the bike1 object.

If we use an initializer to initialize values inside a class, we need to pass the corresponding value during the object creation of the class.

var bike1 = Bike(name: "Mountain Bike")

Here,

  • "Mountain Bike" is passed to the name parameter of init()
  • self represents the bike1 object
  • self.name is equal to Mountain Bike

Example: Swift Initializer

class Bike {

  // properties with no default values
  var name: String
  var gear: Int

  // assign value using initializer
  init(name: String, gear: Int){
    self.name = name
    self.gear = gear
  }
}

// object of Person with custom initializer 
var bike1 = Bike(name: "BMX Bike", gear: 2)

print("Name: \(bike1.name) and Gear: \(bike1.gear)")

Output

Name: BMX Bike and Gear: 2

In the above example, we have created the class named Bike with two properties name and gear.

We have used the custom initializer to assign values to the properties of the class.

Finally, while creating an object of the Bike class, we have passed values "BMX Bike" and 2 as arguments.


Struct Vs Class in Swift

Even though the working of struct and class looks similar, there exist some major differences between them.

1. Class is the concept of object-oriented programming. So, it provides some OOP features like Inheritance where we can derive a new class from the existing class.

However, inheritance of structs is not available.

To learn more about inheritance, visit Swift Inheritance.

2. Classes are of reference type. This means each instance of a class shares the same copy of data. For example,

class Bike {
  var color: String

  init(color:String) {
    self.color = color
  }
}

var bike1 = Bike(color: "Blue")

var bike2 = bike1

bike1.color = "Red"
print(bike2.color)  // prints Red

As you can see here, we are changing the color for the bike1 object. However, the color is changed for the bike2 object as well.

On the other hand, structs are of the value type. This means each instance of a struct will have an independent copy of data. For example,

struct Bike {
  var color: String

  init(color:String) {
    self.color = color
  }
}

var bike1 = Bike(color: "Blue")

var bike2 = bike1

bike1.color = "Red"
print(bike2.color)  // prints blue

As you can see here, we are changing the color for the bike1 object. However, the color of the bike2 object is unchanged.

Did you find this article helpful?