Latest Post

SwiftUI NavigationView and NavigationStack SwiftUI Show progress of the task using SwiftUI ProgressView Flutter Vs React Native which is better?

Structures and Classes in Swift

Difference between struct and class in swift : Struct is basically know as value type object where as class is called as reference type object.

Struct

Struct  is the value type object, it is the member-wise initialiser. it is called as value type because it passes the value to  the function,  when u use the struct whole thing is duplicated.it points the value of the  object. it shows he value of the object

Defining a Struct

struct School {
    var clothes: String
    var shoes: String
}

Struct can be initialised as shown below 

var stev = School(clothes: "Shirt", shoes: "puma")

Accessing  the member  of Struct in Swift 
stev.clothes
stev.shoes
Example : CGPoint , CGRect

Classes

Class is the reference type of object. it passes the reference data to the function . when class is used each object points to the same original  object if you change one they all will change. it show the reference of the real object
class School {
    var clothes: String
    var shoes: String
}
Class can be initialised as shown below
class School {
    var clothes: String
    var shoes: String

    init(clothes: String, shoes: String) {
        self.clothes = clothes
        self.shoes = shoes
    }
}

Accessing the properties of class

var rob = School(clothes: "Pants", shoes: "rebook")
rob.clothes
rob.shoes
  • Ex. UIViewUIViewController
 

Struct Vs Class swift

Difference between struct and class in swift

Additional capabilities  only available in class compare to struct in swift?

 * Type Casting : We can check the type of the class in runtime.

    * Reference Counting : Allow more than 1 reference to the class instance

 * Inheritance : A class can inherit the property or characteristic of other class but in struct we cannot.

 * De initialisation : we can de-initialise the class resource at any instant.

Memory Allocation of Struct and Class in swift

  • Struct are allocated in Stack memory .
  • Reference of the class  object can be created on the Stack but the properties of the class object are store in the heap.

Class and Struct  Dispatch method

 Struct are static Dispatch where as class uses method Dispatch but the compiler will use static dispatch

When to use Struct and When to use Class in swift

Class is used when we need the control identity , Choose Struct  when we no need of control identity

Leave a Reply

Your email address will not be published.