The main difference between structs and classes in Swift lies in the way they store and manage data (value type vs. reference type), as well as additional features that only classes have.
Here are the main differences:
1.Type: value Type vs Reference Type
Comparison: swift
- Data Storage value type(independent copy) Example: var a1 = b1 creates a new copy
class
Reference Type (Reference to the same object)
var a1 = b1 (pointing to the same object )
Example Value Type (struct):
struct Person {
var name: String
}
var person1 = Person(name: "Andry")
var person2 = person1
person2.name = "Budi"
print(person1.name) // Andry
print(person2.name) // Budi
Example Reference Type (class):
class Person {
var name: String
init(name: String) {
self.name = name
}
}
var person1 = Person(name: "Andry")
var person2 = person1
person2.name = "Budi"
print(person1.name) // Budi
print(person2.name) // Budi
2.Inheritance
struct : does not support inheritance
class : support inheritance
Example:
class Animal {
var name: String = "Unknown"
}
class Dog: Animal {
var breed: String = "Bulldog"
}
3.Deinitializers
struct : no deinit.
class : has deinit for cleanup when the object is removed from memory.
class MyClass {
deinit {
print("Object is being deallocated")
}
}
4.Mutability (Data Changes)
struct: requires the mutating keyword to change properties from within the method.
class: bebas mengubah properti tanpa keyword tambahan.
struct Counter {
var count = 0
mutating func increment() {
count += 1
}
}
If you're building a Swift/iOS app, most data models can simply use structs. But for UI components and complex logic with inheritance, classes are more appropriate.