This repo is a thorough answer to the question
What happens if multiple modules implement the same extension to a Foundation type?
Let's try to answer it.
What you've got here are three projects that all declare an instance variable collision
on String
:
- StringExtensionOne is a Swift Package that declares its value to be
"String Extension One"
- StringExtensionTwo is a Swift Package that declares its value to be
"String Extension Two"
- WhenModulesCollide is a project that declares its value to be
"String+Collision.swift"
The WhenModulesCollide
project links to both the StringExtensionOne
and StringExtensionTwo
packages. However, neither packages are imported in ViewController.swift
. Similarly, and the local module's declaration in String+Collision.swift
is commented out. With no declaration anywhere, the code doesn't compile.
Experiment with different combinations of:
- importing either, neither, or both of these packages in
ViewController.swift
- uncommenting the local module's implementation in
String+Collision.swift
Build & run the code after making your change. You'll see the result in the UI & in the logs, or in Xcode if there's an error.
Think of what you'd expect to happen in these situations. And if you don't feel like investigating, just click to see the answer.
What happens if the `collision` property is never defined?
That's the state this project starts in. It doesn't compile and gives you an error:
Value of type 'String' has no member 'collision'
What happens if I either import a module or enable the local module's definition, but not both?
Whichever extension you enabled to be linked to your code will win.
What happens if I import a module that collides with my local extension?
The local extension wins. "String+Collision.swift"
is shown in the display & in the log.
What happens if I import two modules with conflicting extensions?
This is a compiler error.
Ambiguous use of 'collision'