---
title: Tránh as! (force cast)
impact: CRITICAL
impactDescription: Ngăn chặn crash ứng dụng do ép kiểu sai thực tế. Force-cast là nguyên nhân phổ biến gây lỗi runtime.
tags: swift, ios, casting, force-cast, safety
---

## Tránh as! (force cast)

Không sử dụng ép kiểu bắt buộc `as!`, thay vào đó nên dùng `as?` kết hợp với kiểm tra null (optional binding). Force-cast sẽ khiến ứng dụng bị crash ngay lập tức nếu đối tượng không thuộc kiểu dữ liệu mong đợi.

**Incorrect (force cast):**

```swift
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! MyCustomCell
```

**Correct (safe cast):**

```swift
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? MyCustomCell else {
    fatalError("Không thể cast cell sang MyCustomCell")
}
```

**Tools:** SwiftLint (force_cast)
