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

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.

主站蜘蛛池模板: 湘乡市| 彰化县| 葫芦岛市| 宝丰县| 高要市| 志丹县| 喜德县| 阳朔县| 宾川县| 成都市| 昌乐县| 延边| 区。| 石台县| 家居| 都江堰市| 崇明县| 饶平县| 贵南县| 平舆县| 视频| 辽阳市| 兴业县| 开远市| 昔阳县| 兴城市| 张北县| 赣州市| 阳曲县| 青田县| 盐源县| 台江县| 九龙县| 绿春县| 湾仔区| 宁河县| 富阳市| 肥城市| 砀山县| 金华市| 山东|