”;
Classes in Swift are building blocks of flexible constructs. Similar to constants, variables and functions the user can define class properties and methods. Swift provides us with the functionality that while declaring classes the users need not create interfaces or implementation files. Swift allows us to create classes as a single file and the external interfaces will be created by default once the classes are initialized.
Benefits of having Classes
-
Inheritance acquires the properties of one class to another class.
-
Type casting enables the user to check class type at run time.
-
Deinitializers take care of releasing memory resources.
-
Reference counting allows the class instance to have more than one reference.
Common Characteristics of Classes and Structures
-
Properties are defined to store values
-
Subscripts are defined as providing access to values
-
Methods are initialized to improve functionality
-
Initial states are defined by initializers
-
Functionality is expanded beyond default values
-
Confirming protocol functionality standards
Definition of a Class in Swift
In Swift, a class is defined using a class keyword along with the name of the class and curly braces({}). The name of the class always starts with a capital letter such as Employee, not employee and the curly braces contain an initializer, properties methods of the class.
-
Properties − The constants and variables associated with the class are known as the properties of the structure. They are commonly used to define the characteristics of the class. A class can have multiple properties.
-
Methods − Functions associated with the class are known as the methods of the class. They are commonly used to define behaviour associated with the class. They can have parameters and return values. A single class can have multiple methods.
-
Initializer − It is a special method associated with a class. An initializer is used to set up the initial state of a class instance. It is defined using the init keyword. It is called when we create an instance of the class. It can have parameters and default values.
Syntax
Following is the syntax of the class −
class nameClass { // Properties Property 1 : Type Property 2 : Type // Initializer init(){ // statement } // Methods func functionName(){ // Statement } }
Example
In the following Swift example, we create a class named markStruct with three properties such as studname of String type, mark and mark2 of Int type.
class student{ var studname: String var mark: Int var mark2: Int }
Swift Class Object
An object is known as the instance of the class. It is created according to the blueprint defined by the class. A single class can have multiple objects and they are independent of each other, which means if we modify one instance that doesn”t affect other instances. We can create an object of the class by calling the class initializer. Using this initializer, we can initialize each property by passing the initial value along with the name of the property.
Syntax
Following is the syntax of the class instance −
var objectName = ClassName(propertyName1: Value, propertyName2: value)
Example
In the following Swift example, we will create an instance of Marks.
class Marks { var mark1: Int var mark2: Int var mark3: Int } // Creating a class object using an initializer var myObj = Marks(mark1: 10, mark2: 20, mark3: 30)
Accessing the Properties of the Class in Swift
To access the properties of the class we can use a class object followed by a dot(.) and the name of the property. We can also modify the values of the properties with the help of dot(.) syntax.
Syntax
Following is the syntax for accessing the properties of the class −
classObjectName.PropertyName
Following is the syntax for modifying the properties of the class −
classObjectName.PropertyName = value
Example
Swift program to access and modify the properties of a class.
// Defining a class struct Employee { var name: String var department: String var salary: Int // Initializer init(name: String, department: String, salary: Int){ self.name = name self.department = department self.salary = salary } } // Creating an instance of the Employee class var emp = Employee(name: "Suman", department: "Designing", salary: 33000) // Accessing the values of the properties using dot notation print("Employee Details:") print("Name: (emp.name)") print("Department: (emp.department)") print("Salary: (emp.salary)") // Modifying the values of the properties using dot notation emp.salary = 40000 // Displaying the updated values print("nUpdated Value:") print("Salary: (emp.salary)")
Output
It will produce the following output −
Employee Details: Name: Suman Department: Designing Salary: 33000 Updated Value: Salary: 40000
Accessing the Methods of the Class in Swift
To access the methods of the class we can use dot notation. Here a class instance is followed by a dot(.) and a method name to access methods.
Syntax
Following is the syntax for accessing the method of the class −
classInstanceName.methodName
Example
Swift program to access the methods of the class.
// Defining a class class Parallelogram { // Properties of class var base: Double var height: Double // Initializer init(base: Double, height: Double){ self.base = base self.height = height } // Method to calculate the area of the Parallelogram func calculateParallelogramArea() -> Double { return base * height } } // Create an instance of the Parallelogram class var myObj = Parallelogram(base: 10.0, height: 9.0) // Calling the calculateParallelogramArea() method let area = myObj.calculateParallelogramArea() print("Area of the Parallelogram: (area)")
Output
It will produce the following output −
Area of the Parallelogram: 90.0
Class as a Reference Type in Swift
In Swift, classes are reference types, which means that when we assign a class to a structure or constant or pass it to a function as a parameter, a reference of the existing object will used. So, when we make changes to one instance will reflect in all the references of that instance.
Example
Swift program to demonstrate class as a reference type.
// Defining a class class Student { // Properties var name: String var age: Int // Initializer init(name: String, age: Int){ self.name = name self.age = age } } // Creating an instance of the Student class var stud = Student(name: "Kunal", age: 22) // Assigning stud to details // Here details have the reference of stud object var details = stud // Modifying the values of the properties // Here the modification will affect the stud instance // because it passed as a reference-type details.name = "Mohina" details.age = 40 print("student 1: name-(stud.name) and age-(stud.age)") print("student 2: name-(details.name) and age-(details.age)")
Output
It will produce the following output −
student 1: name-Mohina and age-40 student 2: name-Mohina and age-40
”;