在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:

#if TARGET_IPHONE_SIMULATOR
    // Simulator
#else
    // Device
#endif

这些是编译时宏,在运行时不可用。

我如何在Swift中实现同样的目标?


当前回答

斯威夫特5.2.4 Xcode 11.7


 #if targetEnvironment(simulator)

 #endif

其他回答

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

我希望这个扩展可以派上用场。

extension UIDevice {
    static var isSimulator: Bool = {
        #if targetEnvironment(simulator)
        return true
        #else
        return false
        #endif
    }()
}

用法:

if UIDevice.isSimulator {
    print("running on simulator")
}

运行时,但比这里的大多数其他解决方案更简单:

if TARGET_OS_SIMULATOR != 0 {
    // target is current running in the simulator
}

或者,你可以调用一个Objective-C helper函数来返回一个使用预处理器宏的布尔值(特别是如果你已经在你的项目中混合了)。

编辑:不是最好的解决方案,特别是在Xcode 9.3中。请看HotJard的回答

Xcode 11, Swift 5

    #if !targetEnvironment(macCatalyst)
    #if targetEnvironment(simulator)
        true
    #else
        false        
    #endif
    #endif

我在Swift 3中使用了下面的代码

if TARGET_IPHONE_SIMULATOR == 1 {
    //simulator
} else {
    //device
}