I’m enjoying learning Swift, but it didn’t take long before I took to Google looking for #if 0 in Swift. #if 0
(pronounced, by me at least, as “pound if zero”) is a quick and easy way to get around C’s lack of support for nested multiline comments. Consider this snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h> #include <math.h> int main(void) { float s = 0; /* printf("DEBUG: Calculating sin(x)\n"); s = sin(45); /* Calculate sin */ */ printf("sin(45) is %f\n", s); } |
In C (and C++, and Objective-C), that’s a big no-no. GCC proclaims warning: "/*" within comment
and then unceremoniously dies with error: unexpected expression before '/' token
. Even the syntax highlighter I use in WordPress trips up on it and leaves the last */
without decoration. Amusing.
So rather than using /*
and */
to comment out a block of code, I’d rely on #if 0
, like this:
1 2 3 4 |
#if 0 printf("DEBUG: Calculating sin(x)\n"); s = sin(45); /* Calculate sin */ #endif |
Voilá. Problem solved. Once I’m done experimenting or troubleshooting a bug I can either delete the code within the #if 0
block, or remove the #if
and #endif
pair.
Of course I tried using my trusty #if 0
when coding in Swift, only to find that it isn’t supported. This didn’t shock me; #if
is a C preprocessor directive after all. But I still wanted a way to quickly comment out a block of code and not worry about whether there were other comments within the block. So, again, I went straight to Google looking for #if 0 in Swift. What I should have been searching for is nested multiline comments in Swift..
Straight from the horses mouth (also known as the Swift Programming Language Guide): Unlike multiline comments in C, multiline comments in Swift can be nested inside other multiline comments. … Nested multiline comments enable you to comment out large blocks of code quickly and easily, even if the code already contains multiline comments.
Well, isn’t that handy! Now I can comment out large blocks of code at will by placing /*
and */
around them. Life is good. 🙂
Nested comments can be confusing. There is #if false and #endif in swift.