Search code examples
macrosswiftimportpreprocessorconditional-compilation

How do I write universal Swift code for both iOS and macOS. In cocoa I could use #ifdef, what do I do now?


For our project we always used one source file for both platforms: iOS and macOS (previously OS X). Right now I am migrating to Swift. Unfortunately there is some files which need

import Cocoa

and on iOS

import UIKit

previously we did

#ifdef __MAC_OS_X_VERSION_MAX_ALLOWED
#import <Cocoa/Cocoa.h>
#else
#import <UIKit/UIKit.h>
#endif

How can this be done in Swift? I don't like to write each class twice just because there is no macros anymore.


Solution

  • Use:

    #if os(OSX)
        import Cocoa
    #elseif os(iOS)
        import UIKit
    #endif