Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 657
JackPearse Avatar asked Oct 13 '14 12:10

JackPearse


People also ask

How do I run a swift code in Xcode?

Note: On OSX Yosemite and Xcode 6.1 and above you can run the Swift Compiler by just typing swiftc in the command line. The Swift Compiler is what compiles your Swift code to binary, and it's called swiftc. Now compile and run hello. swift.


1 Answers

Use:

#if os(OSX)
    import Cocoa
#elseif os(iOS)
    import UIKit
#endif
like image 180
Kirsteins Avatar answered Sep 24 '22 00:09

Kirsteins