Question

Is it possible in Objective-C to create a block inline and use its return type? For example, can I create a block that returns a BOOL, have it be inline, and use its return type for an assignment.

BOOL b = <inline block that returns BOOL> { // unsure of the syntax / legality of this
    return YES; // will be more logic in here, that is why I want to use a block.
};

I am having trouble with the block syntax, and am unsure if a block can be created inline. I have checked the following resources with no avail.

Thankyou for your time and patience if this happens to be impossible, or very easy.

Was it helpful?

Solution 2

What you would need to do use the following:

BOOL b = ^(){ return YES; }();

This actually creates the block and then calls it. It's not nice to read though, so you may as well just do something like this:

BOOL b = NO;
{
    // Other stuff, will be local
    b = YES;
}

OTHER TIPS

A different way to achieve that result is a "compound statement expression":

BOOL b = ({
    BOOL result;
    // other local variables and stuff, computing "result"
    result; // The last expression is the value of this compound statement expression. 
});

This is a GCC extension to the C language (and understood by Clang as well). It looks similar to a block, but is something different.

I don't really see a good reason for this, but you can indeed do it. Just put the function call parentheses after the block

BOOL b = ^{
    return YES;
}();

This is really identical to declaring and using it separately, then inlining it.

BOOL (^returnB)() = ^{
    return YES;
};
BOOL b = returnB();

You don't need to create a Block to do this. If you're not assigning the Block itself to a variable to reuse later, then it is pointless. Just do the necessary calculations and put the result into b.

BOOL b = ^BOOL(NSString * s, int n){
    unichar c = [s characterAtIndex:n];
    return c == "w";
}(myString, 5);

should just be

unichar c = [myString characterAtIndex:5];
BOOL b = c == "w";

If you're worried about scoping for some reason, use a compound statement (enclosing the lines in braces) or a statement expression.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top