---
title: Không khai báo tên trùng lặp trong cùng scope
impact: LOW
impactDescription: Shadowing biến gây nhầm lẫn về giá trị nào đang được dùng, dẫn đến bug khó phát hiện.
tags: swift, ios, shadowing, naming, code-quality
---

## Không khai báo tên trùng lặp trong cùng scope

Tránh re-declare một biến với tên giống biến bên ngoài scope (variable shadowing). Trường hợp ngoại lệ hợp lý duy nhất là optional binding (`if let user = user`), nhưng cần hạn chế và sử dụng shorthand `if let user` (Swift 5.7+).

**Incorrect (shadowing gây nhầm lẫn):**

```swift
class CartViewModel {
    var items: [CartItem] = []

    func calculateTotal(items: [CartItem]) -> Double {
        // `items` parameter shadowing `self.items`!
        return items.reduce(0) { $0 + $1.price }  // items nào đây??
    }

    func applyDiscount(_ discount: Double) {
        var discount = discount * 0.01  // re-declare discount - confusing!
        if discount > 0.5 { discount = 0.5 }
        totalPrice *= (1 - discount)
    }
}
```

**Correct (tên rõ ràng, không shadow):**

```swift
class CartViewModel {
    var items: [CartItem] = []

    func calculateTotal(for cartItems: [CartItem]) -> Double {
        return cartItems.reduce(0) { $0 + $1.price }
    }

    func applyDiscount(_ discountValue: Double) {
        let cappedDiscount = min(discountValue * 0.01, 0.5)
        totalPrice *= (1 - cappedDiscount)
    }
}

// Optional binding: Dùng shorthand Swift 5.7+
func loadProfile(user: User?) {
    guard let user else { return }  // OK - shorthand, không shadow
    displayName.text = user.name
}
```

**Tools:** SwiftLint (`shadowed_variable`), Xcode Warnings

