Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

namespaces - Swift's standard library and name collision

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.

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?

EDIT: Question answered here (thanks @Martin R for your comment)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...