DEV Community

NalineeR
NalineeR

Posted on

Struct vs Class

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"
    }
}
Enter fullscreen mode Exit fullscreen mode

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

Image description

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")
}
Enter fullscreen mode Exit fullscreen mode

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{

    }
}
Enter fullscreen mode Exit fullscreen mode

Now based on above differences you can easily decide our preference for specific case.

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.

Top comments (0)