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

2

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.

Punchboard answered 13/10, 2014 at 12:10 Comment(0)
A
29

Use:

#if os(OSX)
    import Cocoa
#elseif os(iOS)
    import UIKit
#endif
Affidavit answered 13/10, 2014 at 12:12 Comment(4)
Does that finally mean, that there is still a preprocessor build in with swift?Punchboard
Check out "Preprocessor directives" in the manual: developer.apple.com/library/ios/documentation/Swift/Conceptual/…Affidavit
Oh, I didn't see this chapter. This is quite helpful. Thanks a lot.Punchboard
Is there an even better way to make it one liner? ;)Companionship
T
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
Tun answered 15/11, 2020 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.