問題描述
我知道 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 的標準庫和名稱沖突的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!