The Main difference in Class and Structure
Classes are reference types. Structures are value types. Classes have an inheritance that allows one class to inherit the characteristics of another. Structures do not support inheritance.
Class ( Reference Types )
- Reference Type
- When you copy a reference type, each instance shares the data. The reference itself is copied, but not the data it references. When you change one, the other changes too.
- Inheritance
- Classes have an inheritance that allows one class to inherit the characteristics of another.
- Initializer
- We have to define the initializer manually.
- Storage
- Class instances are stored on the heap.
- Thread Safe
- Classes are not fully thread−safe.
Example :
class EmployeeList {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.grade = grade
}
}
let emp1 = EmployeeList(name: "Dixit Akabari", age: 27)
let emp2 = emp1
emp2.name = "Ms Dhoni"
print("emp1 name: \(emp1.name)")
print("emp2 name: \(emp2.name)")
OutPut :
emp1 name: Ms Dhoni
emp2 name: Ms Dhoni
Structure ( Value types )
- Reference Type
- When you copy a value type each instance keeps a unique copy of the data. If you change one instance, the other doesn’t change too.
- Inheritance
- Classes have an inheritance that allows one class to inherit the characteristics of another.
- Initializer
- We have to define the initializer manually.
- Storage
- Class instances are stored on the heap.
- Thread Safe
- Classes are not fully thread−safe.
Example :
struct EmployeeListStruct {
var name: String
var age: Int
}
let emp1 = EmployeeListStruct(name: "Dixit Akabari", age: 8)
var emp2 = emp1
emp2.name = "MS Dhoni"
print("Employee1 name: \(emp1.name)")
print("Employee2 name: \(emp2.name)")
OutPut :
Employee1 name: Dixit Akabari
Employee2 name: MS Dhoni
Conclusion
Now Hopefully, you’ll be easier to reason about choosing between a class or a struct.
Comments
Post a Comment