Search code examples
swiftpackagevisibilitynaming

Swift Package's extension property's visibility


When defining a property as an Extension in a Swift Package, if it was created with internal visibility, is it safe to define a property of the same name on the side that uses it? Or could there be problems caused by the One Definition Rule?

The code below is an example of an extension to add:

extension Collection {
    var isNotEmpty: Bool {
        return !isEmpty
    }
}

Solution

  • This wouldn't be a problem at all, because the extensions belong to different modules. It's only the "simple names" of the members that are the same. The fully-qualified names are different, and the actual symbol names that are written to the binary are different too (See mangling rules - you can see that the module name is included too).

    Since you declared it internal, other module's code won't be able to access it at all - their code can only access the member that they declared.

    Due to a bug that hasn't been fixed as of now (Swift 5.8), even if you declared your member to be public, other modules can still declare their own member with the same name. (See this old question of mine) The member in your module is "hidden", in a way - code in their module will only be able to access the member declared in their module.

    It would only be a problem if there are two modules that both declare the member with the same name, and a third module tries to use that member. The compiler wouldn't know which module's member it is referring to.