在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
当前回答
除了其他答案。
在Objective-c中,确保你包含了TargetConditionals。
# include < TargetConditionals.h >
在使用TARGET_OS_SIMULATOR之前。
其他回答
更新信息截至2018年2月20日
看起来@russbishop有一个权威的答案,使这个答案“不正确”-即使它似乎工作了很长一段时间。
检测应用程序是否正在构建的设备或模拟器在Swift
以前的回答
基于@WZW的回答和@Pang的评论,我创建了一个简单的实用结构。这个解决方案避免了@WZW的答案产生的警告。
import Foundation
struct Platform {
static var isSimulator: Bool {
return TARGET_OS_SIMULATOR != 0
}
}
使用示例:
if Platform.isSimulator {
print("Running on Simulator")
}
swift 4.1已过时。请改用#if targetEnvironment(模拟器)。源
要检测Swift中的模拟器,您可以使用构建配置:
在Swift Compiler中定义此配置- d IOS_SIMULATOR - Custom Flags >其他Swift Flags 在下拉菜单中选择Any iOS Simulator SDK
现在你可以使用这个语句来检测模拟器:
#if IOS_SIMULATOR
print("It's an iOS Simulator")
#else
print("It's a device")
#endif
你也可以扩展UIDevice类:
extension UIDevice {
var isSimulator: Bool {
#if IOS_SIMULATOR
return true
#else
return false
#endif
}
}
// Example of usage: UIDevice.current.isSimulator
斯威夫特5.2.4 Xcode 11.7
#if targetEnvironment(simulator)
#endif
我希望这个扩展可以派上用场。
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