Scope is all about which code has access to which other pieces of code. Swift makes it relatively easy to understand because all scope is defined by curly brackets ({}
). Essentially, code in curly brackets can only access other code in the same curly brackets.
To illustrate scope, let's look at some simple code:
var outer = "Hello" if outer == "Hello" { var inner = "World" print(outer) print(inner) } print(outer) print(inner) // Error: Use of unresolved identifier 'inner'
As you can see, outer
can be accessed from both in and out of the if
statement. However, since inner
was defined in the curly brackets of the if
statement, it cannot be accessed from outside of them. This is true of structs, classes, loops, functions, and any other structure that involves curly brackets. Everything that is not in curly brackets is considered to be at
global scope, meaning that anything can access it.