5

Objective C has preprocessor, Swift has compilation conditions that allows to use different code for different environments, for example for debug or release build:

#if DEBUG
    print("debug message")
    doDebugAction()
#else
    doReleaseAction()
#endif

Can I add code that compiles only for SwiftUI preview? Something like:

#if targetEnvironment(swiftUIPreview) 
    static func mock() -> SomeStruct {
        // fill random data
    } 
#endif
General Failure
  • 2,421
  • 4
  • 23
  • 49
  • Does this answer your question? [How do you check if SwiftUI is in preview mode?](https://stackoverflow.com/questions/58759987/how-do-you-check-if-swiftui-is-in-preview-mode) – ReDetection Jun 30 '22 at 14:57

1 Answers1

8

Unfortunately it doesn't exist any compilation condition afaik, but you can use ProcessInfo:

ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
Rico Crescenzio
  • 3,952
  • 1
  • 14
  • 28