1

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
    }
}
3
  • Please show a code example of "define a property of the same name on the side that uses it" to make things clearer. Do you mean you still want to refer to the original property in your newly defined property? How would that be possible? The property is internal, isn't it?
    – Sweeper
    Commented May 12, 2023 at 1:23
  • I want to use the newly added property in my module. That's why it is defined as internal visibility. However, since this is a common name, I want to know if there is a problem with other users defining it with the same name on the side of using my module. Commented May 12, 2023 at 2:10
  • Ah I see. There wouldn't be any problems at all, even if you declared it public.
    – Sweeper
    Commented May 12, 2023 at 2:12

1 Answer 1

2

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.