在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
当前回答
斯威夫特4
现在可以使用targetEnvironment(模拟器)作为参数。
#if targetEnvironment(simulator)
// Simulator
#else
// Device
#endif
为Xcode 9.3更新
其他回答
使用下面的代码:
#if targetEnvironment(simulator)
// Simulator
#else
// Device
#endif
适用于Swift 4和Xcode 9.4.1
我希望这个扩展可以派上用场。
extension UIDevice {
static var isSimulator: Bool = {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}()
}
用法:
if UIDevice.isSimulator {
print("running on 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")
}
除了其他答案。
在Objective-c中,确保你包含了TargetConditionals。
# include < TargetConditionals.h >
在使用TARGET_OS_SIMULATOR之前。
从Swift 1.0开始,对我来说有用的是检查除了arm之外的架构:
#if arch(i386) || arch(x86_64)
//simulator
#else
//device
#endif