Struct vs Class

Nalinee
2 min readApr 25, 2023

--

struct and class are the pillars of any Object Oriented Language. Main part is deciding when to use which one. To get the answer of this question we need know how they differ in properties. Let’s check one by one -

1. Reference vs Copy — Classes work on reference type whereas Structs work on Copy type. Suppose you create an instance A and later you create another instance B by assigning A to it. Now check their effects based on their types —
1. Class-> Change in A or B will show change in other one also because they are pointing to same address.
2. Struct -> change in A or B will not affect other because both the instances are separate. B is like a independent copy of A.

2. Inheritance — Classes allow us to inherit other classes whereas Structs don’t support inheritance.

Class inheritance — Below code snippet shows how class B has inherited class A.

class classA{
var name = “”
}
class classB:classA{
let type = “”

func updateName(){
//accessing property of inherited class A
name = “updated name”
}
}

Struct inheritance — Structs don’t support inheritance hence complier will give error if we go for it.

3. init — Structs come with a default init function including all the properties which is known as _property-wise initialisation_. Whereas in Class you need to write your own init function.

class classA:NSObject{
var name:String

init(userName:String){
name = userName
}
}

struct structA{
var name:String
var skills:String
}

func demoOfInit(){
let classObj = classA(userName: "class")
let structObj = structA(name: "struct", skills: "default init")
}

4. deinit function — Class provides us the deinit function whereas in struct there is no such function.

class classA:NSObject{
var name:String

init(userName:String){
name = userName
}

deinit{}
}

One example can be Modals -> In modals we go for Structs because we generally don’t need their references or inheritance as they are usually used as independent objects.

--

--