Differences between structure and class

Lakshmi K
2 min readMar 2, 2022

--

Most of times we use classes and structures when we are developing an iOS app, so what are these two ? and what is differences between these two ?. Structures and classes are simple but they play a main role and very important for app development.

First let’s see some similarities between structures and classes.

  1. These are like blue prints of an object , which will define variables to store properties , methods for executing a block of code ,etc.
  2. Both can define initialisers to setup initial state while object is getting created , this can be done by using init() method in both structures and classes.
  3. Both can get extended with extensions. so we can add some extra functionalities to them.
  4. Both can work with generics to provide flexible and reusable codes.
  5. Both can confirm to protocols and implement delegate patterns.

now let’s see what are differences between them —

  1. Classes are reference types , where as structures are value types.
  2. By using classes we can take advantage of inheritance where one(sub) class get inherit from another(super) class and use some of allowed functionalities of super class. Where as in structures we don’t have inheritance concept.
  3. In classes we can use deinit method to de initialise any of properties we created before class object is destroyed. In structures we don’t deinit method.

After theoretical explanation, let’s go for practical implementation of both

Structures Declaration:

struct Day { // Declaring structure , its contains variable and methods

var time: Int = 12

init() { //Initialiser

}

}

var monDay = Day()

var tuesDay = monDay // #1

tuesDay.time = 10 //#2

print(monDay.time) // prints 12

print(tuesDay.time) // prints 10

in above example monDay.time and tuesDay.time prints different values,

#1 -when we create tuesDay object by assigning monDat object, tuesDay object creates new copy of Day class and maintain that object at separate memory address

#2 — so monDay and tuesDay objects both contains different values (here time variable) even though both are of same object type.

Classes Declaration:

class AnotherDay {

var time: Int = 12

deinit { // Deinitialiser

}

}

var saturDay = AnotherDay()

var sunDay = saturDay // #1

sunDay.time = 10 // #2

print(saturDay.time) //prints 10

print(sunDay.time) // prints 10

In the above example when sunDay object is assigned to saturDay object , it will point to AnotherDay class reference (to same memory address which is pointed by saturDay object) , instead of creating new copy of the class. due to this if we change time variable value using either saturDay or sunDay objects , both object will have the same values.

That’s all for structures and classes differences , in another article I will come up with detailed implementation of classes and structures.

--

--