8

I was just quickly playing with blocks today and I came across the error:

NSString *(^testBlock)(int) = ^(int option) {
    if (option == 1) return @"ONE";
    if (option == 2) return @"TWO";
    return nil;
};
NSLog(@"OUTPUT: %@", testBlock(4));
Return type 'void *' must match previous return type 'NSString *' when block literal has unspecified explicit return type

As I really wanted to return nil if "1" or "2" were not input I decided to simply cast the final return back to an NSString using:

NSString *(^testBlock)(int) = ^(int option) {
    if (option == 1) return @"ONE";
    if (option == 2) return @"TWO";
    return (NSString *) nil;
};

This works just fine, I was just curious if this was the correct solution or even bad practice as I have never thought about casting nil before?

1
  • Thanks for reformatting the code, Sulthan.
    – fuzzygoat
    Jan 10, 2013 at 13:51

1 Answer 1

14

It's not the best approach.

You should correct the first line to this:

NSString *(^testBlock)(int) =  ^NSString*(int option){
    if(option == 1) return @"ONE"; 
    if(option==2) return @"TWO";
    return nil;
};

This way the block literal has the return type specified and the error goes away. Correctly.

EDIT: Adding explanation on the initial error:

A block without a return type will have the return type inferred by the compiler (which doesn't happen with functions). When you have 2 return statements in the block with different types (note that nil is void*) the compiler can't infer the return type and reports an error. To fix that error you have to manually specify a return type to avoid ambiguity for the compiler.

As a good practice, never return different types from the same block unless you are using polymorphism.

4
  • Nice, the solution looks clear, any reference to the documentation explaining return type requirements for this case ?
    – A-Live
    Jan 10, 2013 at 13:37
  • Thank you sqreept, I had missed off declaring the return type in the definition, I was then incorrectly (as you say) trying to fit the problem elsewhere, I simply had not spotted the missing return type. Much appreciated.
    – fuzzygoat
    Jan 10, 2013 at 13:49
  • Just the official Apple docs: developer.apple.com/library/ios/#documentation/cocoa/conceptual/…
    – sqreept
    Jan 10, 2013 at 13:51
  • Thanks for expanding on the original answer with your edit, very helpful.
    – fuzzygoat
    Jan 11, 2013 at 7:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.