Skip to Content

Struct vs Class trong Swift

1. Giới thiệu

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

2. Value Type vs Reference Type

// 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!)

3. Mutation

// 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!

4. Inheritance

// Struct KHÔNG hỗ trợ inheritance struct Animal {} // struct Dog: Animal {} // Error! // Class hỗ trợ inheritance class AnimalC {} class DogC: AnimalC {}

5. Initializers

// 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 } }

6. Deinitializers

// Struct KHÔNG có deinit // Class có deinit class Resource { deinit { print("Cleaning up...") } }

7. Khi nào dùng Struct

// ✅ 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 }

8. Khi nào dùng Class

// ✅ 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() } }

9. Performance

// 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

10. Bảng so sánh

FeatureStructClass
TypeValueReference
Inheritance
Deinit
Memberwise init✅ Auto❌ Manual
Mutating keyword✅ Cần❌ Không cần
Identity (===)
Thread-safe✅ By default❌ Cần xử lý

📝 Tóm tắt

  • 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
Last updated on