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

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.

主站蜘蛛池模板: 金堂县| 家居| 凌源市| 灵川县| 合作市| 汽车| 平泉县| 安新县| 西城区| 岗巴县| 梧州市| 吴江市| 大同市| 上思县| 资兴市| 杭州市| 馆陶县| 德阳市| 剑川县| 桐庐县| 织金县| 高阳县| 马鞍山市| 祥云县| 达拉特旗| 开远市| 浑源县| 萝北县| 延津县| 绥化市| 贵溪市| 新乡县| 无锡市| 五家渠市| 涿鹿县| 青海省| 南部县| 玉树县| 同仁县| 昭觉县| 河北省|