如何在Swift中有条件地编译tvOS

Pop*_*Pop 11 ios swift tvos

如何在Swift语言的同一文件中有条件地编译iOS和tvOS的代码?我已经尝试了Apple文档中提到的所有Objective-C样式#ifTARGET_OS_TV,以及其他一些答案.但我还没有为Swift代码找到一个可行的解决方案.

Lub*_*bos 22

#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
Run Code Online (Sandbox Code Playgroud)


noe*_*cus 8

Apple 在您的应用程序中定位 Apple TV的标题下也涵盖了这一点

清单 1-1 Objective-C 中 tvOS 的条件化代码

 #if TARGET_OS_TV
     NSLog(@"Code compiled only when building for tvOS.");
 #endif
Run Code Online (Sandbox Code Playgroud)

清单 1-2 Swift 中 tvOS 的条件化代码

#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.")
}
Run Code Online (Sandbox Code Playgroud)

  • 非常有助于了解 Objective-C 和 Swift 语法之间的差异。 (2认同)

Pop*_*Pop 6

#if <build configuration> && !<build configuration>
statements
#elseif <build configuration>
statements
#else
statements
#endif
Run Code Online (Sandbox Code Playgroud)

其中构建配置可以是:-
os(abc) 其中 abc 的有效值为 OSX、iOS、watchOS、tvOS、Linux
arch(abc) 其中 abc 的有效值为 x86_64、arm、arm64、i386

请参阅此处的苹果文档: