Bỏ qua để đến nội dung

Struct vs Class

Struct là value type, Class là reference type. Chọn đúng loại quan trọng cho performance và behavior.

// Struct - Value Type
struct PointS {
var x: Int
var y: Int
}
var p1 = PointS(x: 10, y: 20)
var p2 = p1 // Copy
p2.x = 100
print(p1.x) // 10 (unchanged)
// Class - Reference Type
class PointC {
var x: Int
var y: Int
init(x: Int, y: Int) { self.x = x; self.y = y }
}
let c1 = PointC(x: 10, y: 20)
let c2 = c1 // Same reference
c2.x = 100
print(c1.x) // 100 (changed!)
// Struct với let - immutable hoàn toàn
let structPoint = PointS(x: 10, y: 20)
// structPoint.x = 100 // Error!
// Class với let - có thể thay đổi properties
let classPoint = PointC(x: 10, y: 20)
classPoint.x = 100 // OK!
// Struct KHÔNG hỗ trợ inheritance
struct Animal {}
// struct Dog: Animal {} // Error!
// Class hỗ trợ inheritance
class AnimalC {}
class DogC: AnimalC {}
// Struct - memberwise initializer tự động
struct Person {
var name: String
var age: Int
}
let p = Person(name: "Alice", age: 25)
// Class - phải viết initializer
class PersonC {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
// Struct KHÔNG có deinit
// Class có deinit
class Resource {
deinit {
print("Cleaning up...")
}
}
// ✅ Dùng Struct khi:
// - Encapsulate simple data
// - Copy semantics phù hợp
// - Không cần kế thừa
// - Thread-safe by default
struct Coordinate {
var latitude: Double
var longitude: Double
}
struct Money {
var amount: Decimal
var currency: String
}
// ✅ Dùng Class khi:
// - Cần kế thừa
// - Cần deinit
// - Cần shared mutable state
// - Identity quan trọng hơn equality
class ViewController {
// Shared instance, identity matters
}
class NetworkSession {
// Cần deinit để cleanup connections
deinit { disconnect() }
}
// Struct - thường nhanh hơn
// - Stack allocation (nhỏ)
// - Copy-on-write optimization
// Class - overhead nhiều hơn
// - Heap allocation
// - Reference counting
// - Potential memory leaks
Feature Struct Class
Type Value Reference
Inheritance
Deinit
Memberwise init ✅ Auto ❌ Manual
Mutating keyword ✅ Cần ❌ Không cần
Identity (===)
Thread-safe ✅ By default ❌ Cần xử lý

  • Struct: Value type, copy, no inheritance
  • Class: Reference type, shared, inheritance
  • Ưu tiên Struct cho data models
  • Dùng Class khi cần inheritance/identity
  • Struct thread-safe hơn
  • Apple khuyến nghị: Struct by default