Swift#39;s standard library and name collision(Swift 的标准库和名称冲突)
问题描述
我知道 Swift 不使用命名空间,但名称是在每个模块中定义的.首先,我不太明白这是如何避免名称冲突的 - 请随意详细说明.
I know that Swift doesn't use namespaces, but that names are defined within each module. First of all, I don't understand very well how this avoids name collisions -feel free to elaborate.
不过,我的主要问题是:假设我想要一个不使用 NSTreeNode 的树结构,所以我创建了自己的名为TreeNode"的类.现在假设 Apple 决定在 Swift 的标准库中包含一个用于构建树的类,并且正如预期的那样,他们将其命名为TreeNode".那会发生什么?我的自定义 TreeNode 将与标准库的 TreeNode 发生冲突...在这种情况下我是否必须更改所有代码?或者,Apple 会承诺 Swift 的标准库在未来不会改变?
Nevertheless, my main question is: Let's say I want a tree structure without using NSTreeNode, so I make my own class named "TreeNode". Now let's say that Apple decides to include a class to build trees in Swift's standard library, and, as expected, they name it "TreeNode". What happens then? My custom TreeNode will collide with Standard Library's TreeNode... Will I have to change all my code in cases like that? Or maybe Apple will promise that Swift's Standard Library will not change in the future?
这里回答了问题(感谢@Martin R 的评论)
Question answered here (thanks @Martin R for your comment)
推荐答案
Swift 中的命名空间是隐式的.所有类和其他符号都属于定义它们的目标(模块).因此,如果您定义类 String
,则完全限定名称将是 MyTarget.String
.当发生名称冲突时,您必须在类名前加上定义它的模块(框架),除非在当前模块中定义了具有该名称的类 - 此类优先且不需要前缀.
Namespacing in Swift is implicit. All classes and other symbols belong to the target (module) they are defined in. So if you define a class String
the fully qualified name would be MyTarget.String
. When there is a name collision, you have to prefix the class name with the module (framework) it is defined in, except when there is a class with that name defined in the current module - this class takes precedence and does not need to be prefixed.
struct String {
var swiftString = ""
}
var a = String()
var b = Swift.String()
因此,如果您创建了您的类 TreeNode
并且 Apple 后来也添加了一个 TreeNode
,如果您只使用一个模块并且您不会需要改变任何东西.如果您想使用 Swift 的 TreeNode
,则需要将其称为 Swift.TreeNode
.
So if you create your class TreeNode
and Apple later adds a TreeNode
as well, your name would take precedence if you are using only one module and you wouldn't need to change anything. If you would want to use Swift's TreeNode
, you would need to refer to it as Swift.TreeNode
.
这篇关于Swift 的标准库和名称冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Swift 的标准库和名称冲突


- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01