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. Commented 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.

Sign up to request clarification or add additional context in comments.

4 Comments

Nice, the solution looks clear, any reference to the documentation explaining return type requirements for this case ?
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.
Thanks for expanding on the original answer with your edit, very helpful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.