Class and Object in Swift
Last Updated :
28 Apr, 2025
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:
- Properties: variables or constants that store values for each object of the class.
- Methods: functions that provide functionality for the objects of the class.
- 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.
- Subscripts: special methods that allow access to the values of the object using subscript syntax, such as object[index].
- Extensions: blocks of code that add new functionality to an existing class without modifying its original definition.
- 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:
- Using the class name and parentheses: var objectName = ClassName()
- Using the class name and initializer arguments: var objectName = ClassName(arguments)
- Using the new keyword and the class name: var objectName = new ClassName()
- Using a factory method: a static or class method that returns an object of the class. For example, var objectName = ClassName.create()
- 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
|
A class is a blueprint or template for creating objects.
| An object is an instance or a specific example of a class.
|
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.
|
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.
|
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.
|
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.
Similar Reads
Singleton Class in Swift Singleton is a creational design pattern that makes sure there is just one object of its kind and provides all other code with a single point of access to it. Singletons have essentially identical benefits and drawbacks as global variables. Despite being quite useful, they prevent your code from bei
4 min read
Sorting an Array in Swift Swift support different type of collections and array is one of them. An array is an ordered collection of the same type of values like int, string, float, etc., you are not allowed to store the value of another type in an array(for example, an int type can only store integer values, not string valu
5 min read
Swift - Classes Classes and Objects are building blocks of the Object-Oriented-Programming Paradigm. Class is a logical entity or a user-defined data type that has its own data members and member functions which can be accessed inside the class or outside it depending upon the access control allowed on each member.
8 min read
Closures in Swift In Swift, Closures are known as self-contained blocks of functionality that can be passed around and used inside your code. They are quite similar to blocks in C and Objective-C and to lambdas in other programming languages. Closures can also capture and store references to any constants and variabl
9 min read
String Functions and Operators in Swift A string is a sequence of characters that is either composed of a literal constant or the same kind of variable. For eg., "Hello World" is a string of characters. In Swift4, a string is Unicode correct and locale insensitive. We are allowed to perform various operations on the string like comparison
10 min read
Escaping and Non-Escaping Closures in Swift In Swift, a closure is a self-contained block of code that can be passed to and called from a function. Closures can be passed as arguments to functions and can be stored as variables or constants. Closures can be either escaping or non-escaping. An escaping closure is a closure that is called after
5 min read