Stripping print and debugPrint in Swift for release builds

When building an app for release with Swift you should make sure that any of the print and debugPrint statements you used when building and debugging the app are disabled.  The reason for this is that if you leave them in then they will unnecessarily slow down the app since every write to console output takes time.

In Swift you can easily do this by redeclaring the print and debugPrint functions using these two lines of code…

func debugPrint(items: Any..., separator: String = " ", terminator: String = "\n") {}

func print(items: Any..., separator: String = " ", terminator: String = "\n") {}

We simply declare the functions again but with empty implementations of {}.  When you’re building and testing your app just comment these two lines, but when complete make sure you uncomment them before release.

You should place these two lines at the top-level of your code.  That means, do not put it inside a class, extension or protocol declaration.  A good place to put them is at the top of your AppDelegate file, before the AppDelegate class and not inside it.

Alternatively, simply create a brand new Swift file in your project and call it something like ‘ReleasePrint.swift’ and put the code in there.  Basically, it can be anywhere as long as it is top-level and not inside another class.

Finally, you may find it useful to always see the output from print and debugPrint in the simulator, but never on the device.  If you want to do this you can use the architecture flags to automatically turn the output on and off as follows…

#if !arch(x86_64) && !arch(i386)

func debugPrint(items: Any..., separator: String = " ", terminator: String = "\n") {}
func print(items: Any..., separator: String = " ", terminator: String = "\n") {}

#endif