diff --git a/2019-01-07-import.md b/2019-01-07-import.md new file mode 100644 index 0000000..d9a696a --- /dev/null +++ b/2019-01-07-import.md @@ -0,0 +1,498 @@ +--- +title: Swift Import Declarations +author: Mattt +category: Swift +excerpt: >- + One of the first lessons we learn as software developers + is how to organize concepts and functionality into discrete units. + But what happens when namespaces collide + and declarations lurk in the shadows? +status: + swift: 4.2 +--- + +--- +title: Swift Import 声明 +author: Mattt +category: Swift +excerpt: >- + 作为软件开发人员,我们学到的第一课是如何将概念和功能组织成独立的单元。但是,当命名空间冲突和声明隐藏在阴影时,会发生什么呢? +status: + swift: 4.2 +--- + +One of the first lessons we learn as software developers +is how to organize concepts and functionality into discrete units. +At the smallest level, +this means thinking about types and methods and properties. +These pieces then form the basis of one or more modules, +which may then be packaged into libraries or frameworks. + +作为软件开发人员,我们学到的第一课是如何将概念和功能组织成独立的单元。在最小的层级上,这意味着思考类型、方法和属性。这些东西构成了模块(module)的基础,而模块又可以被打包成为 library 或者 framework。 + +In this way, +import declarations are the glue that holds everything together. + +在这种方式中,import 声明是将所有内容组合在一起的粘合剂。 + +Yet despite their importance, +most Swift developers are familiar only with their most basic form: + +尽管 import 声明非常重要,但大部分 Swift 开发者都只熟悉它的最基本用法: + +```swift +import <#module#> +``` + +This week on NSHipster, +we'll explore the other shapes +of this most prominent part of Swift. + +本周的 NSHipster 中,我们将探索 Swift 这个最重要的功能的其他用法。 + +--- + +An import declaration allows your code to access symbols +that are declared in other files. +However, if more than one module +declares a function or type with the same name, +the compiler may not be able to tell which one you want to call in code. + +import 声明允许你的代码访问其他文件中声明的符号。但是,如果多个模块都声明了一个同名的函数或类型,那么编译器将无法判断你的代码到底想调用哪个。 + +To demonstrate this, +consider two modules representing the multisport competitions of +[Triathlon](https://en.wikipedia.org/wiki/Triathlon) and +[Pentathlon](https://en.wikipedia.org/wiki/Modern_pentathlon): + +为了演示这个问题,考虑 [铁人三项(Triathlon)](https://zh.wikipedia.org/wiki/三项全能) 和 [铁人五项(Pentathlon)](https://zh.wikipedia.org/wiki/现代五项) 这两个代表多运动比赛的模块: + +A triathlon consists of three events: +swimming, cycling, and running. + +铁人三项 包括三个项目:游泳、自行车和跑步。 + +```swift +// 铁人三项模块 +func swim() { + print("🏊‍ Swim 1.5 km") +} + +func bike() { + print("🚴 Cycle 40 km") +} + +func run() { + print("🏃‍ Run 10 km") +} +``` + +The modern pentathlon comprises five events: +fencing, swimming, equestrian, shooting, and running. + +铁人五项 模块由五个项目组成:击剑、游泳、马术、射击和跑步。 + +```swift +// 铁人五项模块 +func fence() { + print("🤺 Bout with épées") +} + +func swim() { + print("🏊‍ Swim 200 m") +} + +func ride() { + print("🏇 Complete a show jumping course") +} + +func shoot() { + print("🎯 Shoot 5 targets") +} + +func run() { + print("🏃‍ Run 3 km cross-country") +} +``` + +If we import either of the modules individually, +we can reference each of their functions +using their unqualified names without a problem. + +如果我们单独 import 其中一个模块,我们可以通过它们的 非限定(unqualified)名称引用它们的每个函数,而不会出现问题。 + +```swift +import Triathlon + +swim() // OK, calls Triathlon.swim +bike() // OK, calls Triathlon.bike +run() // OK, calls Triathlon.run +``` + +```swift +import Triathlon + +swim() // 正确,调用 Triathlon.swim +bike() // 正确,调用 Triathlon.bike +run() // 正确,调用 Triathlon.run +``` + +But if we import both modules together, +we can't always use unqualified function names. +Triathlon and Pentathlon both include swimming and running, +so a reference to `swim()` is ambiguous. + +但是如果同时 import 两个模块,我们不能全部使用非限定函数名。铁人三项和五项都包括游泳和跑步,所以对 `swim()` 的引用是模糊的。 + +```swift +import Triathlon +import Pentathlon + +bike() // OK, calls Triathlon.bike +fence() // OK, calls Pentathlon.fence +swim() // Error, ambiguous +``` + +```swift +import Triathlon +import Pentathlon + +bike() // 正确,调用 Triathlon.bike +fence() // 正确,调用 Pentathlon.fence +swim() // 错误,模糊不清 +``` + +How do we reconcile this? +One strategy is to use +fully-qualified names +to work around any ambiguous references. +By including the module name, +there's no confusion about whether the program will swim +a few laps in a pool or a mile in open water. + +如何解决这个问题?一种策略是使用 全限定名称(fully-qualified name) 来处理任何不明确的引用。通过包含模块名称,程序是要在游泳池中游几圈,还是在开放水域中游一英里,就不存在混淆了。 + +```swift +import Triathlon +import Pentathlon + +Triathlon.swim() // OK, fully-qualified reference to Triathlon.swim +Pentathlon.swim() // OK, fully-qualified reference to Pentathlon.swim +``` + +```swift +import Triathlon +import Pentathlon + +Triathlon.swim() // 正确,指向 Triathlon.swim 的全限定引用 +Pentathlon.swim() // 正确,指向 Pentathlon.swim 的全限定引用 +``` + +Another way to resolve API name collision +is to change the import declaration +to be more selective about what's included from each module. + +解决 API 名称冲突的另一种方法是更改 import 声明,使其更加严格地挑选需要包含每个模块哪些的内容。 + +## Importing Individual Declarations + +## import 单个声明 + +Import declarations have a form +that can specify individual +structures, classes, enumerations, protocols, and type aliases +as well as functions, constants, and variables declared at the top-level: + +import 声明提供了一种样式,可以指定引入定义在顶层(top-level)的单个结构体、类、枚举、协议和类型别名,以及函数、常量和变量。 + +```swift +import <#kind#> <#module.symbol#> +``` + +Here, +`<#kind#>` can be any of the following keywords: + +这里,`<#kind#>` 可以为如下的任何关键字: + +| Kind | Description | +| ----------- | ----------- | +| `struct` | Structure | +| `class` | Class | +| `enum` | Enumeration | +| `protocol` | Protocol | +| `typealias` | Type Alias | +| `func` | Function | +| `let` | Constant | +| `var` | Variable | + +| Kind | Description | +| ----------- | ----------- | +| `struct` | 结构体 | +| `class` | 类 | +| `enum` | 枚举 | +| `protocol` | 协议 | +| `typealias` | 类型别名 | +| `func` | 函数 | +| `let` | 常量 | +| `var` | 变量 | + +For example, +the following import declaration adds only the `swim()` function +from the `Pentathlon` module: + +例如,下面的 import 声明只添加了 `Pentathlon` 模块的 `swim()` 函数: + +```swift +import func Pentathlon.swim + +swim() // OK, calls Pentathlon.swim +fence() // Error, unresolved identifier +``` + +```swift +import func Pentathlon.swim + +swim() // 正确,调用 Pentathlon.swim +fence() // 错误,无法解析的标识 +``` + +### Resolving Symbol Name Collisions + +### 解决符号名称冲突 + +When multiple symbols are referenced by the same name in code, +the Swift compiler resolves this reference +by consulting the following, in order: + +当代码中多个符号被同一个名字被引用时,Swift 编译器参考以下信息,按优先级顺序解析该引用: + +1. Local Declarations +2. Imported Declarations +3. Imported Modules + +1. 本地的声明 +2. 单个导入(import)的声明 +3. 整体导入的模块 + +If any of these have more than one candidate, +Swift is unable to resolve the ambiguity +and raises a compilation error. + +如果任何一个优先级有多个候选项,Swift 将无法解决歧义,进而引发编译错误。 + +For example, +importing the `Triathlon` module +provides the `swim()`, `bike()`, and `run()` methods. +The imported `swim()` function declaration from the `Pentathlon` +overrides that of the `Triathlon` module. +Likewise, the locally-declared `run()` function +overrides the symbol by the same name from `Triathlon`, +and would also override any imported function declarations. + +例如,整体导入的 `Triathlon` 模块会提供 `swim()`、`bike()` 和 `run()` 方法,但从 `Pentathlon` 中单个导入的 `swim()` 函数声明会覆盖 `Triathlon` 模块中的对应函数。同样,本地声明的 `run()` 函数会覆盖 `Triathlon` 中的同名符号,也会覆盖任何单个导入的函数声明。 + +```swift +import Triathlon +import func Pentathlon.swim + +// Local function shadows whole-module import of Triathlon +func run() { + print("🏃‍ Run 42.195 km") +} + +swim() // OK, calls Pentathlon.swim +bike() // OK, calls Triathlon.bike +run() // OK, calls local run +``` + +```swift +import Triathlon +import func Pentathlon.swim + +// 本地的函数会遮住整体导入的 Triathlon 模块 +func run() { + print("🏃‍ Run 42.195 km") +} + +swim() // 正确,调用 Pentathlon.swim +bike() // 正确,调用 Triathlon.bike +run() // 正确,调用本地的 run +``` + +The result of calling this code? +A bizarre multi-sport event involving +a few laps in the pool, +a modest bike ride, +and a marathon run. +_(@ us, IRONMAN)_ + +那这个代码的运行结果是?一个古怪的多运动比赛,包括在一个泳池里游几圈的游泳,一个适度的自行车骑行,和一个马拉松跑。_(@ 我们, 钢铁侠)_ + +{% warning %} +If a local or imported declaration collides with a module name, +the compiler first consults the declaration +and falls back to qualified lookup in the module. + +如果本地或者导入的声明,与模块的名字发生冲突,编译器首先查找声明,然后在模块中进行限定查找。 + +```swift +import Triathlon + +enum Triathlon { + case sprint, olympic, ironman +} + +Triathlon.olympic // references local enumeration case +Triathlon.swim() // references module function +``` + +```swift +import Triathlon + +enum Triathlon { + case sprint, olympic, ironman +} + +Triathlon.olympic // 引用本地的枚举 case +Triathlon.swim() // 引用模块的函数 +``` + +The Swift compiler doesn't communicate and cannot reconcile +naming collisions between modules and local declarations, +so you should be aware of this possibility +when working with dependencies. + +Swift编译器不会通知开发者,也无法协调模块和本地声明之间的命名冲突,因此使用依赖项时,你应该了解这种可能性。 + +{% endwarning %} + +### Clarifying and Minimizing Scope + +### 澄清和缩小范围 + +Beyond resolving name collisions, +importing declarations can also be a way to +clarify your intent as a programmer. + +除了解决命名冲突之外,import 声明还可以作为澄清程序员意图的一种方法。 + +If you're, +for example, +using only a single function from a mega-framework like AppKit, +you might single that out in your import declaration. + +例如,如果只使用 AppKit 这样大型框架中的一个函数,那么你可以在 import 声明中单独指定这个函数。 + +```swift +import func AppKit.NSUserName + +NSUserName() // "jappleseed" +``` + +This technique can be especially helpful +when importing top-level constants and variables, +whose provenance is often more difficult to discern +than other imported symbols. + +顶层常量和变量的来源通常比其他的导入符号更难识别,在导入它们时,这个技术尤其有用。 + +For example, +the Darwin framework exports --- +among other things --- +a top-level `stderr` variable. +An explicit import declaration here +can preempt any questions during code review +about where that variable is coming from. + +例如,Darwin framework 提供的众多功能中,包含一个顶层的 `stderr` 变量。这里的一个显式 import 声明可以在代码评审时,提前避免该变量来源的任何疑问。 + +```swift +import func Darwin.fputs +import var Darwin.stderr + +struct StderrOutputStream: TextOutputStream { + mutating func write(_ string: String) { + fputs(string, stderr) + } +} + +var standardError = StderrOutputStream() +print("Error!", to: &standardError) +``` + +## Importing a Submodule + +## import 子模块 + +The final form of import declarations +offers another way to limit API exposure: + +最后一种 import 声明样式,提供了另一种限制 API 暴露的方式。 + +```swift +import <#module.submodule#> +``` + +You're most likely to encounter submodules +in large system frameworks like AppKit and Accelerate. +These [umbrella frameworks](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/FrameworkAnatomy.html#//apple_ref/doc/uid/20002253-97623-BAJJHAJC) +are no longer considered a best-practice, +but they served an important role during +Apple's transition to Cocoa in the early 00's. + +你很可能在 AppKit 和 Accelerate 等大型的系统 framework 中遇到子模块。虽然这种 [伞架构(umbrella framework)](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/FrameworkAnatomy.html#//apple_ref/doc/uid/20002253-97623-BAJJHAJC) 不再是一种最佳实践,但它们在 20 世纪初苹果向 Cocoa 过渡的过程中发挥了重要作用。 + +For example, +you might import only the +[DictionaryServices](/dictionary-services/) +submodule from the +[Core Services framework](developer.apple.com/documentation/coreservices) +to insulate your code from the myriad deprecated APIs +like Carbon Core. + +例如,你可以仅 import [Core Services framework](developer.apple.com/documentation/coreservices) 的 [DictionaryServices](/dictionary-services/) 子模块,从而将你的代码与无数已废弃的 API(如 Carbon Core)隔离开来。 + +```swift +import Foundation +import CoreServices.DictionaryServices + +func define(_ word: String) -> String? { + let nsstring = word as NSString + let cfrange = CFRange(location: 0, length: nsstring.length) + + guard let definition = DCSCopyTextDefinition(nil, nsstring, cfrange) else { + return nil + } + + return String(definition.takeUnretainedValue()) +} + +define("apple") // "apple | ˈapəl | noun 1 the round fruit of a tree..." +``` + +In practice, +isolating imported declarations and submodules +doesn't confer any real benefit beyond signaling programmer intent. +Your code won't compile any faster doing it this way. +And since most submodules seem to re-import their umbrella header, +this approach won't do anything to reduce noise in autocomplete lists. + +事实上,单独导入的声明和子模块,除了澄清程序员的意图,并不能带来任何真正的好处。这种方式并不会让你的代码编译地更快。由于大部分的子模块似乎都会重新导入它们的伞头文件(umbrella header),因此这种方式也没法减少自动补全列表上的噪音。 + +--- + +Like many obscure and advanced topics, +the most likely reason you haven't heard about +these import declaration forms before +is that you don't need to know about them. +If you've gotten this far making apps without them, +you can be reasonably assured that you don't need to start using them now. + +与许多晦涩难懂的高级主题一样,你之所以没有听说过这些 import 声明样式,很可能的是因为你不需要了解它们。如果你已经在没有它们的情况下开发了很多 APP,那么你完全有理由可以相信,你不需要开始使用它们。 + +Rather, the valuable takeaway here is understanding +how the Swift compiler resolves name collisions. +And to that end, +import declarations are a concept of great import. + +相反,这里比较有价值的收获是理解 Swift 编译器如何解决命名冲突。为此,理解 import 声明是非常重要的。