Swift的标准库和名称冲突 [英] Swift's standard library and name collision
问题描述
我知道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冲突...在这种情况下,我是否需要更改所有代码?还是苹果会承诺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的标准库和名称冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!