In Swift, when may a declaration reuse a name from an outer scope, and when does the compiler reject the redeclaration?
answer
- inner scope versus same scope
- parameters count as outer
- invalid redeclaration
- a read before the inner declaration
basics
~20 sAn inner scope may shadow a global, a parameter or an outer local of the same name; declaring a name twice in one scope is an error, invalid redeclaration. Shadowing is legal but can hide which value a line reads.
solid answer
~40 sSwift resolves a name to the innermost declaration visible at that point. A function body may declare a local with a global's name, or with its own parameter's name, as in `let total = total.rounded()`, and a nested block such as an `if` body or a `do` block may shadow the function's locals in turn. What the compiler rejects is two declarations of one name in the same scope: `invalid redeclaration of 'lines'`. A second rule is about order: reading a local before its declaration in the same function fails with `use of local variable 'tax' before its declaration`, but only when no outer declaration of that name exists. If one does, the earlier line quietly reads the outer value. That quiet case is why reviewers watch shadowing in long functions.
code
swift · 13 lineslet currency = "EUR" // global
func receiptTotal(total: Double, express: Bool) -> String {
let currency = "USD" // shadows the global
let total = total.rounded() // shadows the parameter
if express {
let total = total + 15 // shadows again, inner block only
return "\(currency) \(total)"
}
return "\(currency) \(total)"
}
print(receiptTotal(total: 41.6, express: true)) // USD 57.0
print(receiptTotal(total: 41.6, express: false)) // USD 42.0go deeper
Know that a name can be declared once per scope, and that an inner block or a function body may reuse an outer name, which then hides the outer one.
Explain lookup from the innermost scope outward, shadowing a parameter with let total = total.rounded(), and the two diagnostics: invalid redeclaration and use before declaration.
Point out the silent case: a line above an inner declaration reads the outer value without any diagnostic, and say how you would catch it in review of a long function.
Weigh shadowing for refinement against renaming for clarity, and decide what guidance a team gives on it, since the compiler only rejects same-scope duplicates.
## Scopes in a Swift source file A **scope** is a region of code in which a declared name is visible. Swift's scopes nest: 1. **Global scope**: declarations at the top level of a file, such as `let currency = "EUR"`, visible across the module by default. 2. **A function's parameters**, visible throughout its body. 3. **The function body** itself. 4. **Nested blocks** inside it: an `if` or `else` body, a loop body, a `do` block, a closure. When code uses a name, Swift looks it up from the innermost scope outward and takes the first declaration it finds. A declaration that reuses a name from an outer scope **shadows** it: from that declaration to the end of the inner scope, the outer one cannot be reached by that plain name. ## What is allowed - **A local shadowing a global**: `let currency = "USD"` in a function hides the global `currency` for the rest of that function. - **A local shadowing a parameter**: parameters are constants, so `let total = total.rounded()` is the usual way to get an adjusted value under the same name. The right-hand side still reads the parameter, because the new constant is not visible inside its own initializer. - **A block shadowing a function local**: inside `if express { let total = total + 15 }` the inner `total` exists only in that block; after the closing brace the outer `total` is back. - **Optional binding**, `if let total`, is the most common shadowing of all; it is covered with optionals. - **A loop variable**: `for item in items` declares `item` in the loop's own scope. It may shadow an outer `item`, and once the loop ends the outer `item` is visible again with its value untouched, because the loop declared a new constant rather than assigning to the old one. - **A closure's parameters and locals**, which shadow names in the enclosing function the same way a nested block does. ## What the compiler rejects | Code in one scope | Diagnostic | |---|---| | `let lines = 3` then `let lines = 4` | `invalid redeclaration of 'lines'` | | `print(tax)` then `let tax = 0.2`, no outer `tax` | `use of local variable 'tax' before its declaration` | | `let total = 1` then `total = 2` | `cannot assign to value: 'total' is a 'let' constant` | The first is the core rule: a scope may declare a name only once. Unlike some scripting languages, a second `let` with the same name in the same block is not a quiet replacement; it does not compile. The third row is not shadowing at all but reassignment, and it fails for the usual `let` reason. ## The quiet case: reading before an inner declaration The second row has a twist. The "before its declaration" error is reported only when lookup finds **no declaration of that name in an outer scope**. When an outer declaration with the same name exists, a line placed before the inner declaration silently reads the **outer** one: - In a function with `let rate = 1`, the body `if true { print(rate); let rate = 2; print(rate) }` prints `1`, then `2`. - In a function that does `print(currency)` and then `let currency = "USD"`, the first line reads the global `"EUR"` without any diagnostic. No error and no warning: the code compiles and does something a reader may not expect. This is the main practical risk of shadowing in long functions, where a declaration added halfway down changes which value the lines below it see but not the lines above it. ## Using shadowing well - Shadow to **refine** a value under the same meaning: a rounded total, a trimmed string, an unwrapped optional. - Avoid shadowing a name with a **different meaning**, such as reusing `total` for a tax amount; pick a new name. - Keep temporaries in a `do { }` block when you want them gone before the next step of a long function. - In review, treat a shadowing declaration in the middle of a long function as a prompt to check the lines above it. ## Summary Inner scopes may reuse any outer name, parameters included; the same scope may not declare a name twice. A use before a local declaration is an error only when no outer name matches; otherwise it quietly binds to the outer one.
- In a Swift function, a line reads rate before an inner let rate in the same block. When is that an error?Only when no outer `rate` exists. Then the compiler reports `use of local variable 'rate' before its declaration`. If the function or the file already declares a `rate`, the early line compiles and reads that outer value, and only the lines after the inner declaration see the new one. That silent case is the one to catch in review.
- Can a Swift function body declare a local with the same name as its parameter?Yes. Parameters live in a scope outside the body, so `let total = total.rounded()` shadows the parameter, and the initializer still reads the parameter because a constant is not visible in its own initializer. It is the common workaround for parameters being constants; changing the caller's value would need an `inout` parameter instead.
- Saying Swift forbids reusing any name visible from an outer scope
- Believing a second let with the same name in one block replaces the first
- Claiming a read before an inner declaration always triggers an error
- Thinking a function cannot declare a local named like its parameter
- Assuming an inner shadowing declaration still exists after its block ends