Learning Swift
上QQ阅读APP看书,第一时间看更新

Scope

Scope is all about which code has access to other pieces of code. Swift makes it relatively easy to understand because all scopes are defined by curly brackets ({}). Essentially, any code within curly brackets can only access other code within the same curly brackets.

How is scope defined

To illustrate scope, let's look at some simple code:

var outer = "Hello"
if outer == "Hello" {
    var inner = "World"
    println(outer)
    println(inner)
}
println(outer)
println(inner) // Error: Use of unresolved identifier 'inner'

As you can see, outer can be accessed both in and out of the if statement. However, since inner was defined within the curly brackets of the if statement, it cannot be accessed outside it. This is true for structs, classes, loops, functions, and any other structure that involves curly brackets. Everything that is not within any curly brackets at all is considered to be at the global scope, meaning that anything can access it.

Nested types

Sometimes, it can be useful to control the scope yourself. To do this, you can define types within other types:

class OuterClass {
    struct InnerStruct {
    }
}

In this scenario, InnerStruct is only directly visible from within OuterClass. This, however, provides a special scenario that is not there for other control structures such as if statements and loops. If code at the global scope wants to access InnerStruct, it can do so through OuterClass, which it has direct access to:

var inner = OuterClass.InnerStruct()

This can be useful to better segment your code, but it is also great for hiding code that is not useful to any code outside other code. As you program in bigger projects, you will start to rely on Xcode's autocomplete feature more and more. In big code bases, autocomplete can offer a lot of options and nesting types in other types is a great way to reduce unnecessary clutter in the autocomplete list.