官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 富锦市| 吴川市| 永川市| 五大连池市| 泰宁县| 游戏| 吉木萨尔县| 邛崃市| 济宁市| 兰坪| 湖南省| 玛多县| 吉林市| 方山县| 衡阳县| 大理市| 喀喇| 宁远县| 淳化县| 方山县| 临猗县| 当涂县| 建始县| 富源县| 康马县| 绥阳县| 托克托县| 海门市| 从江县| 牟定县| 东兰县| 罗甸县| 兴业县| 灵宝市| 额济纳旗| 西青区| 油尖旺区| 津市市| 青岛市| 金山区| 罗城|