Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
What is the scope of extensions in swift?

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!