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

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.

主站蜘蛛池模板: 定安县| 五家渠市| 宁波市| 沂源县| 禹州市| 茌平县| 仙桃市| 固始县| 泰安市| 米泉市| 巴楚县| 龙州县| 扬州市| 潞城市| 汉川市| 襄城县| 和政县| 蓬莱市| 玛曲县| 界首市| 台南县| 靖西县| 阿巴嘎旗| 且末县| 泸州市| 红原县| 桃江县| 南华县| 晋城| 芜湖县| 随州市| 清新县| 宾川县| 壶关县| 河西区| 盘锦市| 庆元县| 彭州市| 汶上县| 旺苍县| 武陟县|