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:
1 2 3 4 |
func mySlowFunction() { #warning("TODO: Optimize this") // Some slow code here... } |
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:
1 2 3 4 |
struct Configs { #error("Please, provide a real server URL and remove this line") static let serverURL = URL(string: "https://example.com")! } |
Also, you can use these directives in tandem with conditional compilation:
1 2 3 4 5 6 7 |
#if DEBUG #warning("Compiling for debug") #endif #if !os(macOS) #error("This library does not support platforms other than macOS") #endif |
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.