Junior — Middle
What are scopes and how are they used in programming?
sobes.tech AI
Answer from AI
Scope — these are contexts in programming where certain variables, functions, or objects are accessible for use. In iOS development with Swift, for example, scope determines where exactly in the code you can access a variable or function.
Main types of scope:
- Global scope — variables and functions are accessible throughout the entire project.
- Local scope — variables are only accessible within the function, method, or code block where they are declared.
- Class or struct scope — properties and methods are accessible within instances or the type itself.
Using scope helps control access to data, avoid name conflicts, and improve code readability and maintainability.
Example in Swift:
func example() {
let localVariable = 10 // accessible only within the example function
print(localVariable)
}
// print(localVariable) // error, variable is out of scope
let globalVariable = 20 // accessible anywhere in the file
example()
print(globalVariable)