Calling Blocks Inline

I’ve recently discovered an interesting use for blocks in Objective-C. It’s possible to call them inline right after the definition, just like you would do in javascript. Such a block would look something like this:

const NSInteger value = (^NSInteger {
    switch (type) {
        case TypeOne:
            return 1;

        case TypeTwo:
            return 2;

        case TypeUnknown:
        case TypeUnspecified:
            return NSNotFound;

        default:
            return 0;
    }
}());

First of all, this allows us to get the correct value for our variable at the moment of definition, and thus to specify it as const. Also it includes all the code related to calculating our value, which makes it easier to read. Both of these things, however, can be achieved with the GCC code block extension. The major advantage of this approach is the support for the return keyword, which makes it possible to have switches and loops without breaks. The downside is having to repeat the variable type for the block, which is especially annoying when it’s something like UISwipeGestureRecognizerDirection.

One more example:

const BOOL anyValueIsXyz = (^BOOL {
  for (QwertyValue *value in values) {
    if (value.isXyz) {
      return YES;
    }
  }

  return NO;
}());

Edit:

Shkutkov Michael pointed out that the block return type can be inferred from the return statement, so you can disregard what I said about having to repeat the type.

Also, the parens around the block aren’t necessary for the block to run. I added them to make it easier to spot that you’re not assigning the block itself, which should be most useful when the return type is id. If you don’t like the idea, you can safely save two characters by omitting them.

GCD Dispatch Groups With an Additional Level of Inception
Nozbe & iOS 7 – Part 2: What Else Have We Done