I'm learning the swift programming language and recently came across the concept of extensions, where you can extend the functionality of an existing class or struct. For example (source):
extension String {
func trimmed() -> String {
self.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
My question is, other than the file where I write this, what other code does this modification impact?
For example, if I declare an extension to String
in one file, will it affect the behavior of String
in libraries I import? Or if I declare this extension in one file, will it be visible in other files in the same project?
Relatedly, I don't understand how Swift resolves conflicts between extensions. Say for example, I import two libraries which both extend String
. Which one takes effect?
I have tried Googling for terms like "swift extensions scope" and "swift conflicting extensions", and haven't found anything that describes fully how it works. I have also noticed Swift doesn't let me redeclare an extension within a single file, but that doesn't answer my question about how extensions from imports affect each other.
The scope of an extension follows the same rules as when creating structs, classes and other types and variables in swift.
By default the extension is internal
to the module it is created in and so accessible to all files in that module.
You can change that to public
or private
if you wish to.
The collisions you reference would occur if two extensions of the same were visible to each other and added a function with the same signature.
So, if you wanted to create your trimmed()
extension in several files and give it a different implementation in each file you would need to make them all private to avoid any conflict.
Although… that might not be a good idea as it could be quite confusing with several of these in your project.