Swift Byte #6: How to Detect if Application is Running On Simulator?
A quick guide on how to detect if the application is running on simulator or device
Recently, I learned a simpler way for detecting if the application is running on the simulator or not.
With Swift 4.1 and above, you can use target environment to check for it. For example:
#if targetEnvironment(simulator)
print("It's running on simulator")
#else
print("It's running on device")
#endifI seem to remember that the solution was much more complex than the above, where you have to check whether it’s x86_64 or i386 architecture. Stuff like that.
I can also wrap these preprocessor macros into a function so that the codebase is not littered with it. For example:
struct Environment {
...
func isRunningOnSimulator() -> Bool {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}
}Pretty neat right?
Anyway, thanks for still following this newsletter. I know I have been procrastinating. 😬



