在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
当前回答
从Swift 1.0开始,对我来说有用的是检查除了arm之外的架构:
#if arch(i386) || arch(x86_64)
//simulator
#else
//device
#endif
其他回答
我在Swift 3中使用了下面的代码
if TARGET_IPHONE_SIMULATOR == 1 {
//simulator
} else {
//device
}
使用下面的代码:
#if targetEnvironment(simulator)
// Simulator
#else
// Device
#endif
适用于Swift 4和Xcode 9.4.1
达尔文在这里描述了一切。TargetConditionals: https://github.com/apple/swift-corelibs-foundation/blob/master/CoreFoundation/Base.subproj/SwiftRuntime/TargetConditionals.h
TARGET_OS_SIMULATOR—生成的代码将在模拟器下运行
斯威夫特5.2.4 Xcode 11.7
#if targetEnvironment(simulator)
#endif
Xcode 11, Swift 5
#if !targetEnvironment(macCatalyst)
#if targetEnvironment(simulator)
true
#else
false
#endif
#endif