I would like to globally ignore all println()
calls in my Swift code if I am not in a Debug build. I can\'t find any robust step by step instructions for this a
The problem with all these approaches, including mine, is that they do not remove the overhead of evaluating the print
arguments. No matter which of them you use, this is going to be expensive:
print(myExpensiveFunction())
The only decent solution is to wrap the actual print call in conditional compilation (let's assume that DEBUG
is defined only for debug builds):
#if DEBUG
print(myExpensiveFunction())
#endif
That, and only that, prevents myExpensiveFunction
from being called in a release build.
However, you can push back evaluation one level by using autoclosure. Thus, you could rewrite my solution (this is Swift 3) like this:
func print(_ item: @autoclosure () -> Any, separator: String = " ", terminator: String = "\n") {
#if DEBUG
Swift.print(item(), separator: separator, terminator: terminator)
#endif
}
This solves the problem just in the case where you are printing just one thing, which is usually true. That's because item()
is not called in release mode. print(myExpensiveFunction())
thus ceases to be expensive, because the call is wrapped in a closure without being evaluated, and in release mode, it won't be evaluated at all.