Use parens as a hint to Xcode's autoindent

Sometimes I wish Xcode's autoindent would do things a little differently. For example, I like to use C's ternary operator:

NSString *label = [self someBooleanTest]
                  ? [self methodWithASortOfLongishName]
                  : [self anotherMethodWithALongishName];

Unfortunately Xcode (at least Xcode 3) autoindents this code like this:

NSString *label = [self someBooleanTest]
? [self methodWithASortOfLongishName]
: [self anotherMethodWithALongishName];

As a workaround, I use the fact that Xcode likes to align things under parentheses and other opening delimiters:

NSString *label = ([self someBooleanTest]
                   ? [self methodWithASortOfLongishName]
                   : [self anotherMethodWithALongishName]);

This can help with other compound expressions as well:

BOOL rectContainsPoint = ((point.x > NSMinX(rect))
                          && (point.x < NSMaxX(rect))
                          && (point.y > NSMinY(rect))
                          && (point.y < NSMaxY(rect)));

Side note: The reason I parenthesized the subexpressions of the boolean expression above is so I can easily select a subexpression by double-clicking on a parenthesis. This makes it easier to eyeball for correctness. I don't always do this — I probably wouldn't have done it with this particular code — but when I do it's more for this reason than for protecting myself from an operator-precedence mistake.

I have other indentation quibbles that I don't have workarounds for. I'll submit Radars for them when I get around to checking that they're still present in Xcode 4.

UPDATE: Parentheses can also help with autoindenting of blocks:

volumeCalculator = (^(float width, float height, float depth)
                    {
                        return width * height * depth;
                    });

Without the parentheses, the above would look like this, which makes less sense to me:

volumeCalculator = ^(float width, float height, float depth)
{
    return width * height * depth;
};

One thought on “Use parens as a hint to Xcode's autoindent

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.