Has Swift compilation condition for SwiftUI preview environment?
Asked Answered
G

1

8

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
Giotto answered 18/1, 2022 at 14:23 Comment(1)
Does this answer your question? How do you check if SwiftUI is in preview mode?Curtiscurtiss
H
11

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

ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
Hackler answered 18/1, 2022 at 14:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.