17

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)

Community
  • 1
  • 1
George
  • 1,235
  • 10
  • 23
  • Does this http://stackoverflow.com/questions/24002821/how-do-you-use-namespaces-in-swift answer your question ? – Martin R Aug 10 '14 at 18:23
  • 1
    @MartinR No, it doesn't answer my question. Or if it does, I don't understand it. Nested types are not applicable for this issue. The "modules" thing; I still don't get it. But in the case of my TreeNode example, I don't think modules help, because the Standard Library is everywhere. Thanks for your comment, though. – George Aug 10 '14 at 18:28
  • 2
    Have a look at matt's answer http://stackoverflow.com/a/24293236/1187415. - In your case it would be TreeNode and Swift.TreeNode. – Martin R Aug 10 '14 at 18:28
  • Oh! I saw that question before writing mine, but I overlooked this answer. Sorry for that. This one seems to address my question, but not fully: it doesn't say if this is applicable for the Standard Library, nor how. -This is easy to check, though: I'll just try writing a custom "Array" class and see what the compiler says. Many thanks! – George Aug 10 '14 at 18:33

1 Answers1

36

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.

Marián Černý
  • 15,096
  • 4
  • 70
  • 83