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

Scope

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.

How scope is defined

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.

Nested types

Sometimes, it is useful to control 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 like if statements and loops. If code at the global scope wanted to access InnerStruct, it could only do so through OuterClass which it does have direct access to, as shown:

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 offers a lot of options, and nesting types into other types is a great way to reduce unnecessary clutter in the autocomplete list.

主站蜘蛛池模板: 喀喇| 鄂尔多斯市| 紫阳县| 临邑县| 本溪市| 公安县| 寻乌县| 柞水县| 沙雅县| 玛曲县| 威远县| 盐津县| 团风县| 台湾省| 瑞昌市| 香格里拉县| 绥宁县| 温泉县| 双桥区| 昌江| 台湾省| 鹤岗市| 沾益县| 洮南市| 汝州市| 包头市| 将乐县| 井研县| 象州县| 琼结县| 涿鹿县| 安福县| 潼南县| 海阳市| 三亚市| 赤峰市| 枣强县| 沛县| 安乡县| 邹平县| 海门市|