Compile time checking for debug only functions

I work on quite a large project, and we've started using SwiftUI Previews in the last year (I know, very late). We have functions for creating mocks that are surrounded by #if DEBUG to prevent them being used in production code.

However this means that the #Previews need to be surrounded by debug conditions as well, and sometimes this gets forgotten and is only caught when a release build is made twice daily (not at PR stage).

Is there anyway to mark a function as only available in DEBUG, or have the compiler check if a function inside a compile time directive, is called from somewhere that isn't inside the same directive?

1 Like

FWIW, it's the same without involving previews:

#if DEBUG
func foo() {}
#endif

func bar() {
    foo()
}

compiles fine in debug, fails to compile in release.

You can just add custom rule to linter to enforce all previews to be in #if DEBUG.

Yep I know, was just using Previews as the example, as a valid reason to call DEBUG only code from code that isn't in a compile time directive.

I've looked into that with SwiftLint, and it seems like it would require a custom rule based on Swift Syntax which seems like a fair bit of overhead