Swift: Conditional Compilation

Debug spew is a great support mechanism for tracking workflow of your code and to augment debugging. However, leaving that support within your code is not just a poor decor for code stylists, it can also lead to security issues and occasionally to App Review Rejections.
As of Swift 2.1, if all you need is just check whether the code is built with debug or release configuration, you may use the built-in functions:
  • _isDebugAssertConfiguration() (true when optimization is set to -Onone)
  • _isReleaseAssertConfiguration() (true when optimization is set to -O)
  • _isFastAssertConfiguration() (true when optimization is set to -Ounchecked)
It would be used as the following example:
func obtain() -> AbstractThing {
    if _isDebugAssertConfiguration() {
        return DecoratedThingWithDebugInformation(Thing())
    } else {
        return Thing()
Compared with preprocessor macros,
  • ✓ You don’t need to define a custom -D DEBUG flag to use it
  • ~ It is actually defined in terms of optimization settings, not Xcode build configuration
  • ✗ Undocumented, which means the function can be removed in any update (but it should be AppStore-safe since the optimizer will turn these into constants)
  • ✗ Using in if/else will always generate a “Will never be executed” warning.
In addition, you can augment your code with markers that make your navigation through those prints and asserts easier, through the usage of MARK, TODO OR FIXME.
i. MARK : //MARK: viewDidLoad
This will create a horizontal line with functions grouped under viewDidLoad
ii. TODO : //TODO: - viewDidLoad (shown below on the jump bar)
This will group function under TODO: - viewDidLoad category 
iii. FIXME : //FIXME - viewDidLoad
This will group function under FIXME: - You guessed what it does ;-) 



Popular posts from this blog

Bring Boxee Box back to life

Postgres on Synology

Zen-inification - The art of decluttering