Are the #if DEBUG statements really needed for previews in SwiftUI to remove it in a release build? Are the #if DEBUG statements really needed for previews in SwiftUI to remove it in a release build? swift swift

Are the #if DEBUG statements really needed for previews in SwiftUI to remove it in a release build?


NOTE: To be extra clear, you DO NOT need to wrap your preview providers in #if DEBUG conditionals. They are removed from your production build.

I'm a little late, but I just had to make note of this because the confusion is all over the web and it turns out to be quite comical. The release note was under "Resolved Issues" and the title of the resolved ticket was "PreviewProviders aren’t properly removed from built products when archived. (51539802)".

Yeah, it all makes sense now.

The stillThe proof

Annnd Just in case you think they may have changed it later..... more proof

(I'm thorough... maybe too much so)


For your particular case you can remove the #if DEBUG macro, but the issues comes when you want to use some mocks that are inside #if DEBUG macros. The build will fail for Release, because looks like Xcode will still try to build the PreviewProvider, most likely after it is build it strips or unlinks the code from the Release artifact.

#if DEBUGclass MyServiceMock: ServiceMockType {    ...}#endif// Will fail when you try to release.struct ContentView_Previews : PreviewProvider {    static var previews: some View {        ContentView(service: MyServiceMock())    }}

This will work just fine for tests and for preview, but will fail when you try to release.

Despite they are not necessary, you need them if you use any code declared only for Debug. My suggestion is to keep them if you have code used in preview that is available only for debug.

#if DEBUGclass MyServiceMock: ServiceMockType {    ...}#endif...#if DEBUGstruct ContentView_Previews : PreviewProvider {    static var previews: some View {        ContentView(service: MyServiceMock())    }}#endif


It seems to be removed from the 11 GM Seed. The GM seed release notes say (under Resolved Issues):

"The #if/#endif compiler conditionals surrounding PreviewProvider types have been removed from SwiftUI templates. PreviewProviders aren’t properly removed from built products when archived. (51539802)"

Not sure if this means the preview providers aren't currently removed or they fixed the issue and now remove them. I suppose if the template code removes the #if it means Apple believes it is no longer necessary.