Scope
Prerequisites: Functions
Scope is the region of code where a name can be used. In Swift, every pair of curly braces creates a new scope.
Real-world analogy: scopes are nested rooms. From an inner room you can see into the rooms around it, but people outside can't see in.
Example
let taxRate = 0.2 // top-level: visible below
func total(for price: Double) -> Double {
let tax = price * taxRate // inner code can see outer names
return price + tax
}
print(total(for: 100))
if true {
let message = "inside"
print(message)
}
120.0
inside
taxRateis declared outside the function, so the function can read it.taxexists only insidetotal. After the function returns, it's gone.messageexists only inside theifbraces.
Trying to use a name outside its scope is a compile error:
if true {
let message = "inside"
}
print(message)
error: cannot find 'message' in scope
Shadowing
An inner scope can declare a new name that hides an outer one with the
same name. The if let nickname shorthand you've seen is an example —
inside the braces, nickname is the unwrapped value, and outside it's
still the optional.
Keep scope small
Declare values as close as possible to where they're used, and prefer passing values into functions as parameters over reading many outside variables. Small scopes make code easier to follow and change.