Search code examples
swiftobjective-c-categoryswift-extensions

Swift extensions that apply only when you import them


I have some swift extensions I want to across projects.

I'd like to avoid category pollution though, unless those extensions are requested.

Is it possible to write them so that they only apply if I've done a certain import, like:

import MySwiftExtensions

// Use custom extensions
let x = [1,3,5,7].average()
let y = [1,3,5,7].firstWhere { $0 > 3 }
let z = "campervan".make1337()

I could write these as static methods wrapped in a single letter class (eg: ø.average([1,3,5,7]), like lodash) to achieve the same thing but sometimes you get much more concise usage from instance methods.


Solution

  • You wrote:

    I have some swift extensions I want to across projects...

    When I have code that I want to use across projects I create a separate framework to hold that code. Then, when I want to use that code in a new project, I embed the framework in that project. Or, for development purposes, I create a workspace that includes the project and the framework. That allows me to work on both at the same time, and then only embed the framework in the final product when it is time to export it.

    Once the framework is either embedded or in the same workspace, then you should be able to import it into any individual file in your project with:

    import MySwiftExtensions
    

    Any file that does not have the import statement will not have access to the extensions.

    EDIT:

    Here is a link to a blog that describes how to create a Cocoa Touch Framework. And here is another link that describes in detail how to use workspaces to use frameworks in development projects.