18

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
JackPearse
  • 2,922
  • 23
  • 31

2 Answers2

29

Use:

#if os(OSX)
    import Cocoa
#elseif os(iOS)
    import UIKit
#endif
David Snabel-Caunt
  • 57,804
  • 13
  • 114
  • 132
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
6

Since os(OSX) does not work any more on Swift 5/Xcode 12 use:

#if os(macOS)
    import Cocoa
#elseif os(iOS)
    import UIKit
#endif
gundrabur
  • 843
  • 10
  • 12