Swift's standard library and name collision

后端 未结 1 1343
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 21:21

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 f

相关标签:
1条回答
  • 2020-12-03 22:03

    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.

    0 讨论(0)
提交回复
热议问题