How do I conditionally compile code for iOS and tvOS in the same file in the Swift language?
I have tried all the Objective-C style #if
etc. for TARGET_OS_TV
as mentioned in the Apple docs, and some other answers. But I have not found a working solution for Swift code.
#if os(OSX)
// compiles for OS X
#elseif os(iOS)
// compiles for iOS
#elseif os(tvOS)
// compiles for TV OS
#elseif os(watchOS)
// compiles for Apple watch
#endif
This is also covered by Apple under the heading Targeting Apple TV in Your Apps
Listing 1-1 Conditionalizing code for tvOS in Objective-C
#if TARGET_OS_TV
NSLog(@"Code compiled only when building for tvOS.");
#endif
Listing 1-2 Conditionalizing code for tvOS in Swift
#if os(tvOS)
NSLog(@"Code compiled only when building for tvOS.");
#endif
if #available(tvOS 9.1,*) {
print("Code that executes only on tvOS 9.1 or later.")
}
#if <build configuration> && !<build configuration>
statements
#elseif <build configuration>
statements
#else
statements
#endif
Where build configuration can be :-
os(abc) where valid values for abc are OSX, iOS, watchOS, tvOS, Linux
arch(abc) where valid values for abc are x86_64, arm, arm64, i386
See Apple docs here:
I don't have a documentation reference -- though I'd like one -- but I've seen Apple sample code with sections like:
#if os(iOS) || os(tvOS)
#endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With