Scope of Declaration in Swift

The scope of a declaration in Swift refers to the region of the code where the declared name (variable, constant, function, type, etc.) is accessible. In Swift, declaration scope is hierarchical and includes several levels:

  1. Global Scope: Declarations outside of any type or function at the top level of a source file are global. These are accessible throughout the entire module across multiple files unless access control modifiers restrict visibility.
  2. Type-Level Scope: Declarations within types (classes, structs, enums) are accessible within that type’s context. This includes properties and methods.
  3. Function-Level Scope: Variables and constants declared inside a function are local to that function and cannot be accessed outside it.
  4. Block-Level Scope: Variables declared inside blocks of code like if statements, loops, or closures are limited to that block.