Open In App

Class and Object in Swift

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Swift is an object-oriented programming language that supports the concept of classes and objects. In this article, we will learn what are classes and objects, how to define them, and how to use them in Swift.

What is a Class?

A class is a blueprint or template for creating objects. A class defines the properties and methods that are common to all objects of that type. For example, we can define a class named Bike that has properties like name and gears, and methods like start and stop.

Properties of Classes

Properties are variables or constants that store values for each object of a class. Properties can be either stored properties or computed properties. Stored properties store actual values, while computed properties calculate values based on other properties or logic. For example, we can define a computed property called a description that returns a string describing the bike.

Class Declaration

We use the class keyword to declare a class in Swift.

Syntax:

class ClassName {

// class definition goes here

}

For example, we can declare a class named Bike as follows:

Swift




// Author: Nikunj Sonigara
 
class Bike {
    // stored properties
    var name = ""
    var gears = 0
     
    // computed property
    var description: String {
        return "This is a \(name) with \(gears) gears."
    }
     
    // methods
    func start() {
        print("The bike is starting.")
    }
     
    func stop() {
        print("The bike is stopping.")
    }
}
 
// create an object of Bike class
var bike1 = Bike()
 
// assign values to properties
bike1.name = "Hornet"
bike1.gears = 5
 
// access properties and methods
print(bike1.description) // This is a Hornet with 5 gears.
bike1.start() // The bike is starting.
bike1.stop() // The bike is stopping.


Output:

This is a Hornet with 5 gears.
The bike is starting.
The bike is stopping.

Components of Swift Classes

A Swift class can have the following components:

  1. Properties: variables or constants that store values for each object of the class.
  2. Methods: functions that provide functionality for the objects of the class.
  3. Initializers: special methods that are called when an object of the class is created. Initializers can set initial values for the properties or perform other tasks.
  4. Subscripts: special methods that allow access to the values of the object using subscript syntax, such as object[index].
  5. Extensions: blocks of code that add new functionality to an existing class without modifying its original definition.
  6. Protocols: interfaces that define a set of requirements that a class can conform to, such as methods or properties.

What is an Object?

An object is an instance or a specific example of a class. An object has its values for the properties and can use the methods defined by the class. For example, bike1 is an object of the Bike class.

Declaration of Objects

We use the class name followed by parentheses to create an object of a class.

Syntax:

var objectName = ClassName()

For example, we can create another object of the Bike class as follows:

var bike2 = Bike()

Initializing a Swift Object

When we create an object of a class, we can optionally pass some arguments to initialize its properties. These arguments are passed to the initializer method of the class, which sets the initial values for the properties or performs other tasks.

Syntax:

var objectName = ClassName(arguments)

For example, we can define an initializer for the Bike class that takes two arguments: name and gears. The initializer assigns these arguments to the corresponding properties of the object.

Swift




// Author: Nikunj Sonigara
 
class Bike {
    // stored properties
    var name = ""
    var gears = 0
     
    // computed property
    var description: String {
        return "This is a \(name) with \(gears) gears."
    }
     
    // methods
    func start() {
        print("The bike is starting.")
    }
     
    func stop() {
        print("The bike is stopping.")
    }
     
    // initializer
    init(name: String, gears: Int) {
        self.name = name
        self.gears = gears
    }
}
 
var bike3 = Bike(name: "Splendor", gears: 4)
print(bike3.description) // This is a Splendor with 4 gears.


Output:

This is a Splendor with 4 gears.

Ways to Create an Object of a Class

There are different ways to create an object of a class in Swift. Some of them are:

  1. Using the class name and parentheses: var objectName = ClassName()
  2. Using the class name and initializer arguments: var objectName = ClassName(arguments)
  3. Using the new keyword and the class name: var objectName = new ClassName()
  4. Using a factory method: a static or class method that returns an object of the class. For example, var objectName = ClassName.create()
  5. Using a copy constructor: a method that takes another object of the same class and returns a copy of it. For example, var objectName = ClassName(anotherObject)

Difference between Swift class and Object

Parameter/Basis

Class

Object

Definition

A class is a blueprint or template for creating objects.

An object is an instance or a specific example of a class.

Properties and methods

A class defines the properties and methods that are common to all objects of that type.

An object has its own values for the properties and can use the methods defined by the class.

Type

A class is a reference type, which means that references to a class instance share the same data.

A struct is a value type, which means that each reference to a struct instance has its own copy of the data.

Inheritance

A class can inherit from another class, which means that it can inherit the properties and methods of its superclass.

A struct cannot inherit from another struct or class, but it can conform to protocols, which define a set of requirements for the struct.

Deinitializers

A class can have deinitializers, which are methods that are called when an instance of the class is deallocated from memory.

A struct does not have deinitializers, because it does not need to perform any cleanup when it is destroyed.

Conclusion

Classes and objects are essential concepts in object-oriented programming in Swift. They allow us to create and manipulate complex data structures and behaviors. Classes provide the template or blueprint for creating objects, while objects are the specific instances that have their own values and methods. To write effective Swift code, we need to understand how to define, create, and use classes and objects.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads