Search code examples
iosswift3conditional-compilation

Conditional compiling in Swift


I want to use flags to control the compiler in Swift. Like we use #ifdef, #ifndef, #else, #endif in C (and C++, Objective C, ....)

I found the way to do it on the net, but I hit a problem in the following case. Anyone reading will understand what I want. Nevertheless the compiler complains. What is the way to go around? Of course without having to copy two times the same ten or more lines.

#if UseAds
class ViewController: UIViewController,XYZBannerDelegateProtocol {
#else
class ViewController: UIViewController {
#endif

Note that I got the information I am using here: http://en.swifter.tips/condition-compile/ which is similar to what can be found here.

But none of these solves my problem. They only tell me the basic way to do it.


Solution

  • You can use like this :

    class ViewController: UIViewController {
        // Your common functions
    }
    #if UseAds
        extension ViewController: XYZBannerDelegateProtocol {
            // Your delegate methods    
        }
    #endif