在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
当前回答
在现代系统中:
#if targetEnvironment(simulator)
// sim
#else
// device
#endif
就是这么简单。
其他回答
在现代系统中:
#if targetEnvironment(simulator)
// sim
#else
// device
#endif
就是这么简单。
使用下面的代码:
#if targetEnvironment(simulator)
// Simulator
#else
// Device
#endif
适用于Swift 4和Xcode 9.4.1
从Swift 1.0开始,对我来说有用的是检查除了arm之外的架构:
#if arch(i386) || arch(x86_64)
//simulator
#else
//device
#endif
运行时,但比这里的大多数其他解决方案更简单:
if TARGET_OS_SIMULATOR != 0 {
// target is current running in the simulator
}
或者,你可以调用一个Objective-C helper函数来返回一个使用预处理器宏的布尔值(特别是如果你已经在你的项目中混合了)。
编辑:不是最好的解决方案,特别是在Xcode 9.3中。请看HotJard的回答
我在Swift 3中使用了下面的代码
if TARGET_IPHONE_SIMULATOR == 1 {
//simulator
} else {
//device
}