Compiler diagnostic directives in Swift 4.2

Every once in a while, we all find ourselves in situations where we need to leave a reminder note or a message for a particular piece of code for our future selves or colleagues working on the same project. This may be a TODO or FIXME note, for example.

Until Swift 4.2, comments seemed to be the only go-to option for this kind of tasks. While many IDEs can automatically detect and highlight such comments, as far as I know, there is no similar built-in functionality in Xcode or command-line build tools.

Fortunately, Swift 4.2 introduced a couple of compiler directives for accomplishing that and even more. Using #warning directive we can now make the compiler emit warning messages:

If you use this directive, a familiar warning message will appear right next to it in Xcode and in CLI the compiler will output the warning message to the standard error stream (stderr).

#error directive halts the compilation of your code and emits a message with explanation:

Also, you can use these directives in tandem with conditional compilation:

With these directives you can rest assured that your TODO and FIXME notes won’t be left forgotten anymore. Personally, I’m very happy with these additions to the language and hope you’ll find them useful too.

Leave a Reply

Your email address will not be published. Required fields are marked *