Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda