---
title: Delegate Protocol phải là class-only
impact: HIGH
impactDescription: Cho phép dùng weak để tránh retain cycles (memory leak) giữa các đối tượng.
tags: swift, ios, delegate, memory-leak, AnyObject
---

## Delegate Protocol phải là class-only

`weak` chỉ hỗ trợ class types, do đó các delegate protocol phải được khai báo là `class`-based (`AnyObject`). Điều này giúp ngăn chặn retain cycles khi delegate trỏ ngược lại đối tượng sở hữu nó.

**Incorrect (không giới hạn class):**

```swift
protocol MyDelegate {
    func didUpdateData()
}

class MyView {
    var delegate: MyDelegate? // Lỗi: Không thể dùng weak ở đây nếu protocol không là AnyObject
}
```

**Correct (class-only protocol):**

```swift
protocol MyDelegate: AnyObject {
    func didUpdateData()
}

class MyView {
    weak var delegate: MyDelegate? // Đúng: Có thể dùng weak để tránh memory leak
}
```

**Tools:** SwiftLint (class_delegate_protocol)
