在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
当前回答
我希望这个扩展可以派上用场。
extension UIDevice {
static var isSimulator: Bool = {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}()
}
用法:
if UIDevice.isSimulator {
print("running on simulator")
}
其他回答
使用下面的代码:
#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—生成的代码将在模拟器下运行
我希望这个扩展可以派上用场。
extension UIDevice {
static var isSimulator: Bool = {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}()
}
用法:
if UIDevice.isSimulator {
print("running on simulator")
}
在Xcode 7.2(以及更早的版本,但我还没有测试过多少)中,你可以为“任何iOS模拟器”设置一个平台特定的构建标志“-D TARGET_IPHONE_SIMULATOR”。
查看“Swift Compiler - Customer Flags”下的项目构建设置,然后在“Other Swift Flags”中设置标志。当您将鼠标悬停在构建配置上时,可以通过单击“加号”图标来设置特定于平台的标志。
这样做有几个好处:1)你可以在Swift和Objective-C代码中使用相同的条件测试(“#if TARGET_IPHONE_SIMULATOR”)。2)你可以编译出只适用于每个版本的变量。
Xcode构建设置截图
在现代系统中:
#if targetEnvironment(simulator)
// sim
#else
// device
#endif
就是这么简单。