Casting zero in a block

I just played quickly with blocks today, and I came across an 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 

Since I really wanted to return nil if "1" or "2" were not entered, I decided to simply return the final return back to NSString using:

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

This works fine, I was just wondering if this was the right decision or even bad practice, since I had never thought about pouring zero before?

+8
objective-c iphone cocoa-touch objective-c-blocks
source share
1 answer

This is not a good approach.

You should fix the first line:

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

Thus, the type of the return value is indicated in the block literal, and the error disappears. Correctly.

EDIT: adding an explanation of the initial error:

In a block without a return type, the type of returned output will be indicated by the compiler (which does not happen with functions). When you have two return statements in a block with different types (note that nil void *), the compiler cannot infer the type of the returned message and report an error. To fix this error, you need to manually specify the return type to avoid ambiguity for the compiler.

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

+14
source share

All Articles