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. UIView, UIViewController
Struct Vs Class swift
Difference between struct and class in swift
In Swift, both structs and classes are used to define custom data types, but they have some differences in terms of behavior, usage, and characteristics. Here’s an overview of the key differences between structs and classes in Swift, particularly within the context of iOS development:
-
Mutability:
-
Structs: Instances of structs are value types, which means when you assign a struct instance to another variable or pass it as a parameter, a copy of the instance is made. Each instance is independent and has its own data. Structs are generally immutable by default, meaning their properties cannot be modified after creation unless the instance is marked as
var
instead oflet
. - Classes: Instances of classes are reference types. When you assign a class instance to another variable or pass it as a parameter, you’re actually passing a reference to the same instance in memory. Multiple variables can refer to the same instance. Classes are mutable by default, and their properties can be modified even after creation.
-
Structs: Instances of structs are value types, which means when you assign a struct instance to another variable or pass it as a parameter, a copy of the instance is made. Each instance is independent and has its own data. Structs are generally immutable by default, meaning their properties cannot be modified after creation unless the instance is marked as
-
Inheritance:
- Structs: Cannot inherit from other types. They do not support inheritance.
- Classes: Support inheritance, allowing you to create a subclass that inherits properties and methods from a parent class.
-
Initialization:
- Structs: Provide an automatically generated memberwise initializer by default. You can also define your own custom initializers.
- Classes: Do not have automatically generated memberwise initializers. You must define your own initializers for classes.
-
Memory Management:
- Structs: Managed on the stack, and their memory is automatically deallocated when they go out of scope.
- Classes: Managed on the heap, and memory management is handled using reference counting. When there are no more references to a class instance, its memory is deallocated.
-
Performance:
- Structs: Generally have better performance for small, simple data structures due to their value type nature. Copies are cheap and memory locality can be beneficial.
- Classes: Might have a slightly higher overhead due to the reference counting mechanism and potential heap allocations.
-
Copying:
- Structs: Copied when assigned to a new variable or passed as a function parameter. Modifications on the copied instance do not affect the original instance.
- Classes: Referenced when assigned to a new variable or passed as a function parameter. Modifications on the referenced instance affect all references to that instance.
-
Usage:
- Structs: Useful for modeling simple data structures, such as geometric shapes, data points, enums, and other small value types.
- Classes: Useful for modeling more complex objects, creating class hierarchies, and for cases where shared state or inheritance is needed.
In iOS development, both structs and classes are important tools. Generally, structs are preferred for simple data and immutability, while classes are used for more complex objects and when you need reference semantics or inheritance. Your choice between structs and classes depends on the specific requirements of your application and the design of your data model.
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
Key Difference between Class and Struct
- Inheritance: Classes support inheritance while structs do not. This means that a class can inherit properties and behavior from another class, whereas a struct cannot.
- Reference vs Value types: Classes are reference types, which means that when an instance of a class is copied, both the original instance and the new copy refer to the same underlying object. In contrast, structs are value types, which means that when an instance of a struct is copied, a new instance with its own independent values is created.
- Mutability: Classes and structs behave differently when it comes to mutability. In Swift, properties of a struct instance cannot be changed if the instance is declared as a constant (using the
let
keyword). On the other hand, properties of a class instance can be changed regardless of whether the instance is declared as a constant or a variable (using thelet
orvar
keyword). - Memberwise Initializers: Structs automatically generate memberwise initializers, which allow you to initialize all of the struct’s properties at once. Classes do not have memberwise initializers automatically generated by the compiler.
- Copying: As structs are value types, when you pass them as parameters to functions or methods, they are copied, whereas classes are not copied. This means that passing a large instance of a struct to a function can be expensive in terms of memory usage, while passing a class instance does not incur such a cost.
Overall, structs are generally simpler and more lightweight than classes and are best used for small, simple data types. Classes are more powerful and flexible and are better suited for larger, more complex data types that require inheritance and reference semantics.
Example For Struct
struct Customer{
var id: Int = 0
var name: String = ""
init(id:Int,name: String) {
self.id = id
self.name = name
}
}
var customer = Customer(id: 1, name: "Phil")
var anotherName = customer
anotherName.name = customer.name
print(" Print 1 Name for customer is \(customer.name)")
print(" Print 2 Name for AnotherName is \(anotherName.name)")
customer.name = "Dev"
print(" Print 3 Name for customer is \(customer.name)")
print(" Print 4 Name for AnotherName is \(anotherName.name)")
OUTPUT
Print 1 Name for customer is Phil
Print 2 Name for AnotherName is Phil
Print 3 Name for customer is Dev
Print 4 Name for AnotherName is Phil
Here in struct the when customer.name is changed from phil to dev the print 3 name also changed from phil to dev but anothername value is not changed
Example For Class
class Customer{
var id: Int = 0
var name: String = ""
init(id:Int,name: String) {
self.id = id
self.name = name
}
}
var customer = Customer(id: 1, name: "Phil")
var anotherName = customer
anotherName.name = customer.name
print(" Print 1 Name for customer is \(customer.name)")
print(" Print 2 Name for AnotherName is \(anotherName.name)")
customer.name = "Dev"
print(" Print 3 Name for customer is \(customer.name)")
print(" Print 4 Name for AnotherName is \(anotherName.name)")
OUTPUT
Print 1 Name for customer is Phil
Print 2 Name for AnotherName is Phil
Print 3 Name for customer is Dev
Print 4 Name for AnotherName is Dev