- Learning Swift(Second Edition)
- Andrew J Wagner
- 319字
- 2021-07-16 12:33:08
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.
- 異構(gòu)基因共表達(dá)網(wǎng)絡(luò)的分析方法
- 物聯(lián)網(wǎng)信息安全
- Mastering JavaFX 10
- Yii Application Development Cookbook(Second Edition)
- 城市治理一網(wǎng)統(tǒng)管
- 網(wǎng)絡(luò)安全應(yīng)急響應(yīng)技術(shù)實(shí)戰(zhàn)
- 物聯(lián)網(wǎng)之霧:基于霧計(jì)算的智能硬件快速反應(yīng)與安全控制
- 基于性能的保障理論與方法
- jQuery Mobile Web Development Essentials
- 端到端QoS網(wǎng)絡(luò)設(shè)計(jì)
- 網(wǎng)絡(luò)利他行為研究:積極心理學(xué)的視角
- 人人都該都懂的互聯(lián)網(wǎng)思維
- 一本書讀懂物聯(lián)網(wǎng)
- 沖擊:5G如何改變世界
- 5G時(shí)代的大數(shù)據(jù)技術(shù)架構(gòu)和關(guān)鍵技術(shù)詳解