---
title: Tránh ! (force unwrap)
impact: CRITICAL
impactDescription: Loại bỏ nguy cơ crash ứng dụng do truy cập trực tiếp vào giá trị nil của Optional.
tags: swift, ios, optional, force-unwrap, safety
---

## Tránh ! (force unwrap)

Không sử dụng `value!` để lấy giá trị từ một Optional. Force unwrap là một "code smell" nguy hiểm vì nó giả định giá trị luôn tồn tại. Ưu tiên dùng optional binding (`if let`, `guard let`) hoặc nil-coalescing operator (`??`) để xử lý an toàn.

**Incorrect (force unwrap):**

```swift
let url = URL(string: "https://invalid url")!
print(url.absoluteString)
```

**Correct (optional binding):**

```swift
if let url = URL(string: "https://example.com") {
    print(url.absoluteString)
}

// Hoặc dùng guard
guard let url = URL(string: "https://example.com") else {
    return
}
```

**Tools:** SwiftLint (force_unwrapping)
