Fetching articles...

Conditionally compile code for extensions in Swift

I have google this so many times, now I just have to write it down!

When building a framework with functions you can't use in an App Extension, like a ShareExtension or WidgetExtension. Wrap that function or class in an @available like this:


@available(iOSApplicationExtension, unavailable)
func notInExtensions() 
{
    if UIApplication.shared.delegate == nil 
    {
        print("No delegate")
    }
}

Then create a custom Swift compiler flag "APP_EXTENSION" for each extension, and use it like so:


if APP_EXTENSION
    // do whatever else the extension should
else
    notInExtensions()
endif

Nothing more to it!