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!

About

Hello! How nice of you stopping by! ❤️

My name is Olof Thorén, I am an indie developer from Stockholm, Sweden.

I really enjoy creating stuff, and that is the reason why I am doing this. I started working full-time on building apps in 2009.

At the moment my main focus is Feeds, a glorified news and RSS-reader that keeps track of the web for you. I also build Qiozk Solo, white-label magazine apps for (mainly Swedish) publishers. I have published ~75 Solo-apps though most of them are not active today. Aggressive Development has published 15 apps under its own name and many more for other companies.

Please feel free to say hello on twitter @olof_t or email olof@aggressive.se. Don't hesitate to send me comments or feedback on anything I write.