Skip to content

Instantly share code, notes, and snippets.

@T-Pham
Last active July 22, 2016 14:28
Show Gist options
  • Save T-Pham/8a61f84a1f9cd677e0bf7b9ff5eee536 to your computer and use it in GitHub Desktop.
Save T-Pham/8a61f84a1f9cd677e0bf7b9ff5eee536 to your computer and use it in GitHub Desktop.
A wrapper function for Swift conditional compilation statements

Description

This gist provides a wrapper function for Swift conditional compilation statements. If you ever want some code to run in production builds only, this gist might be for you.

WHY???

For no reason. This is just useless! :P

Jk, not really, and here is why:

  • I hate macro. And the like. I don't want to see them in my code. Or at least see them too much. Chances are, you hate them too. So better put them all in one (or two) place.
  • It helps early detect compilation errors!!! Seriously,
#if !DEBUG
// some code should only run in production
utrhoerheugmnaknjiftsyhmdugsottdhieeo // some code your cat wrote and committed while you're sleeping (or drunk)
#endif

The code piece above will compile. It DOES!!! Until you are about to ship your app. So by putting the conditional compilation code outside of the conditional compilation statements, you always know if your cat has secretly modified your code.

Set-up

To use the function, you have first to define a custom Swift compiler flag in your Xcode project:

  • Go to the Build Settings tab of your target or project.
  • Look for the Other Swift Flags setting in Swift Compiler - Custom Flags section.
  • Expand the setting, you should now see Debug and Release.
  • Add -DDEBUG to Debug.

In case you don't use Xcode project, pass -D DEBUG to the command line build statement.

Usage

ifNotDebugDo {
  print("NOT debug")
}
//
// MacroFunctions.swift
//
// Created by Thanh Pham on 7/22/16.
//
func ifNotDebugDo(@noescape closure: Void -> Void) {
#if !DEBUG
closure()
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment