Swift Classes

  Total Views : 140
  Comments : 0
  Keywords : Swift classes are the building blocks of our program code, Swift classes are reference types and the defined values passed as a reference, Swift add properties and methods to classes

Here we will learn classes in swift and how to use swift classes to construct building blocks of our programming code, create and access class values, classes without initializers, how classes will behave as a reference type, protocol adoption in classes and identity operations in swift classes with examples. 

Swift Classes

In swift classes are the building blocks of our programming code in which we declare our methods, properties, variables and etc. to extend the functionality of classes.

 

In swift we can define classes using class keyword and define the properties, methods in classes same as constants, variables and functions.

 

Following are the advantages of using classes in swift programming language.

 

  • We can implement inheritance to acquire the properties from one class to another.
  • Type Casting enable us to check the type of class at runtime.
  • Deinitializers in classes will take care of memory management by releasing unused resources.
  • We can create more than one reference for class instance.

In swift, classes are reference to the same existing instance when they are passed around in our code. Suppose if we assign same class to multiple variables and if we modify one, all the variables with same class reference will be updated with new values because classes are reference types.

 

Unlike other programming languages we don’t need to create any separate interface or implementation files for classes. In swift when we create a classes in single file, automatically that class file will be available for other code blocks to use that functionality in applications.

Syntax of Swift Classes

Generally, in swift classes are defined by using class keyword. Following is the syntax of defining classes in swift programming language.

 

class ClassName {

// Variables

// Methods

// Properities

}

If you observe above syntax we defined class using class keyword along with class name and we defined a required properties, variables and functions in structures based on our requirements in swift programming language.

Swift Define a Class

Following is the example of defining or declaring class in swift programming language.

 

class Room {

var TeacherName : String

var StudentName : String

var MonitorName : String

}

If you observe above example we defined class called “Room” by using class keyword and we defined multiple properties as a string or integer variables inside of class.

Swift Class Instances

Generally, in swift we can access class properties, variables and methods by creating class instance like as shown below.

 

Swift Class Instance with Defined Properties

 

Following is the example of creating instance for newly created class in swift programming language.

 

class Room {

var TeacherName : String

var StudentName : String

var MonitorName : String

}

var sd = Room()

If you observe above example we created instance for Room by using that we can access the properties of class based on our requirements.

Swift Assign and Access Class Properties

Following is the example of assigning and accessing property values from class based on our requirements.

 

class ClassRoom {

var TeacherName : String

var StudentName : String

var MonitorName : String

var StudentMarks: Int

init(TeacherName: String, StudentName: String, MonitorName: String, StudentMarks: Int) {

self.TeacherName = TeacherName

self.StudentName = StudentName

self.MonitorName = MonitorName

self.StudentMarks = StudentMarks

}

}

var studentdetail = ClassRoom(TeacherName: "Rohini Alavala", StudentName: "Suresh Dasari", MonitorName: "Praveen Kumar", StudentMarks: 80)

print("Teacher: \(studentdetail.TeacherName)")

print("Student: \(studentdetail.StudentName)")

print("Monitor: \(studentdetail.MonitorName)")

print("Marks: \(studentdetail.StudentMarks)")

If you observe above example we created a class “ClassRoom” and used initializer to initialize class properties. After that we created an instance of class and assigned same to the variable “studentdetail”. 

 

In class instance we assigned values to the properties and accessing those class properties using variable name.

 

When we run above code in swift playground we will get result like as shown below

 

Teacher: Rohini Alavala

Student: Suresh Dasari

Monitor: Praveen Kumar

Marks: 80

Swift Define a Class without Initializer

In Swift classes we need to use Initializers to initialize the properties which we defined inside of class otherwise compiler will throw an initializer error.

 

Now we will see what will happen in case if we didn’t use initializer for properties which defined in class.

 

Following is the simple example of creating and accessing new class “studentName” and its properties without having any initializer in swift programming language.

 

class studentName

{

var studName : String

}

var stuInfo = studentName(studName: "Suresh Dasari")

print(stuInfo.studName)

If you observe above example we defined a class “studentName” with single property and we didn’t used initializer to initialize the property. After that we created a new instance for the class and assigned that to a variable called “stuInfo

 

When we run above example in swift playground we will get compile time error like as shown below.

 

Swift Define a Class without Initializers

Swift Classes are a Reference Type

In all programming languages, classes are the reference types which means that we can’t store the actual value of class, we only store its reference. Classes use heap memory rather than stack to store the reference of variables. Heap is large pool of memory comparatively with stack memory. 

 

Classes use the heap Memory which mean that when we initialize class with its instance, the value will store in heap memory.

 

Following is the example of showing how structures are values types in swift programming language.

 

class UserDetails {

var name : String

init(name: String) {

self.name = name

}

}

var uinfo1 = UserDetails(name: "Rohini")

var uinfo2 = uinfo1

uinfo2.name = "Suresh"

print(uinfo1.name)

print(uinfo2.name)

If you observe above example we defined a class (UserDetails) and created an instance for the class and assigned to a variable “uinfo1”. After that again we created a new variable “uinfo2” and assigned previously created variable “uninfo1” to new variable.

 

Initially we updated name in variable “uinfo1” after that we assign variable “uinfo1” to “info2” and again we updated name value. 

 

Whenever we update the value in one place same will reflect for all the references in application because classes are reference types in swift programming language.

 

When we run above program in swift playground we will get result like as shown below

 

Suresh

Suresh

This is how classes will behave as a reference types in swift programming language.

Swift Classes Protocol Adoption

In swift, classes will inherit the protocols which mean that we can’t initialize our variables in class level and make a separate property in which we declare the getter and setter property and used in class. 

 

Following is the example of using swift protocols adoption in classes.

 

protocol studprotocol {

var studName: String {get set}

func studentName() -> String

}

class Student : studprotocol {

var studName : String = "Suresh Dasari"

func studentName() -> String

{

return studName

}

}

var student1 = Student()

print(student1.studentName())

If you observe above example we are using protocol adoption along with classes in swift.

 

When we run above program in swift playground we will get result like as shown below

 

Suresh Dasari

This is how the classes inherit protocols in swift programming language.

Swift Identity Operators in Classes

In swift, classes are the reference types so there is possibility that multiple constants and variables will refer the same single class instance. 

 

The identity operators in swift will helps us to check whether the defined constants and variables referring same instance of class or not.

 

Swift provides us two identity operators those are 

 

  • Identical to (===)
  • Not identical to (!==)

By using identical operators we can check whether the constants and variables referring same instance of class or not in swift programming language based on our requirements.

 

Following is the example of using identity operators in swift classes to compare class instances.

 

class studentName

{

var studName : String

init(studName: String) {

self.studName = studName

}

}

var stu = studentName.init(studName: "Rohini Alavala")

var stu1 = studentName.init(studName: "Suresh Dasari")

var result = stu === stu1

var result2 = stu !== stu1

 

print(result)

print(result2)

If you observe above example we created a two variables stu, stu1 after that we created two instances for the same class “studentName”.

 

When we run above example in swift playground we will get result like as shown below

 

false

true

This is how we can use identity operators in classes to compare the instance of classes based on our requirements in swift programming language.

 

Here we need to remember one thing that Identical to (===) is not same as Equals to (==) both are different.

 

Identical to:  It is used to compare whether two variables or constants are referring to same instance of class or not.

 

Equals to: It is used to check whether defined variables value equal or not.

Key Points of Classes

Following are the some of key points which we need to remember while using classes in our swift programming language.

 

  • Classes are the pointers towards the “Objects”
  • Classes allow you to declare properties, methods and subscript.
  • Classes allow to inherit protocols.
  • Classes must have initializer and DE initializer.
  • Classes can inherit from another class.

This is how we can use classes in swift programming language based on our requirements. 

 
 
 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User