How do you check if SwiftUI is in preview mode?

If you like me were looking for an environment variable to use in build scripts which xcode sets when building for SwiftUI previews, it turned out to be ENABLE_PREVIEWS.

SwiftUI were pausing preview when my script updated Info.plist file. To fix that I exit the script at certain point if we are in preview build.

if [ "${ENABLE_PREVIEWS}" = "YES" ]; then
  exit 0;
fi

You can detect this using ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"]. The value will be "1" at runtime when running in the canvas.


Though there is no compilation flag currently available for checking if the active build is intended for the Previews Canvas, I would still recommend using a compiler directive over a runtime check, if it can meet your needs.

For example, this check resolves to true for both the simulator and Previews:

#if targetEnvironment(simulator)
// Execute code only intended for the simulator or Previews
#endif

Negate the condition if you want your code to only execute on physical devices (such as camera-related operations that are otherwise guaranteed to fail).

The runtime check for whether your code is executing for Previews (as given in the accepted answer) probably does not add significant performance overhead, but it still feels a little gross to ship that code IMO. So it's worth at least considering first if your situation requires that level of specificity. If it does, I'd recommend wrapping that code in a compiler check to remove it from release builds.