Thinking about better block syntax (kind-of)

26 Mar

I’m pretty sure we can all agree that block syntax in Objective-C (or rather C) is pretty bad. There’s plenty of evidence.

I use a set of code snippets to help get around this.
Using shorthand like blockLocalVariable that expands to:

<#returnType#> (^<#blockName#>)(<#parameterTypes#>) = ^<#returnType#>(<#parameters#>){
};

However, today I was wondering if macros might be able to help solve this better.
After a little bit of playing around I came up with this…

#define blockParameters(parameters...) parameters

#define block(__blockName__, __returnType__, __blockParameters__, __func__) \
            __returnType__ (^__blockName__)(__blockParameters__) = ^__returnType__(__blockParameters__)__func__

You use it like so:

block(myBlock, int, blockParameters(int a, int b), {
    return a + b;
});

int c = myBlock(1, 2);

While not exactly ideal. It was a somewhat fun exercise.