我该如何在Swift语言的同一文件中有条件地编译iOS和tvOS的代码?
我尝试了所有Objective-C风格的#if
等方式来编写TARGET_OS_TV
,正如在Apple文档和其他答案中所提到的,但我没有找到适用于Swift代码的可行解决方案。
#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
这也是苹果在针对您的应用程序定位Apple TV下所涵盖的内容。
代码清单1-1:Objective-C中的条件代码化
#if TARGET_OS_TV
NSLog(@"Code compiled only when building for tvOS.");
#endif
#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
构建配置可以是以下内容:
os(abc),其中 abc 的有效值为 OSX、iOS、watchOS、tvOS、Linux
arch(abc),其中 abc 的有效值为 x86_64、arm、arm64、i386
请参阅苹果文档此处:
我没有参考文档--虽然我想要一个--但我见过苹果的示例代码,其中有以下章节:
#if os(iOS) || os(tvOS)
#endif