#if 0 In Swift

| | 0 Comments| 8:15 AM

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:

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:

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. 🙂

1 thought on “#if 0 In Swift”

Leave a Reply

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