Return Values
Blocks can also return values. The return type of the block can be specified after the caret, but if you omit it, the compiler will try to infer as much information about the return value as it can, allowing you to write more succinct code. This is a fully qualified block literal for NSArray's -indexesOfObjectsPassingTest: method:
^BOOL (id object, NSUInteger index, BOOL *stop) { return YES; }
But you can reduce it a bit because the return type will be inferred:
^(id object, NSUInteger index, BOOL *stop) { return YES; }
A block that takes no arguments and returns no value can be drastically reduced:
^void (void) { ... } ^(void) { ... } ^{ ... };
All three are equivalent: a block that takes no arguments and returns no values.
Rather than printing out each element of the array, say you want to know which elements contain the word "badger." -indexesOfObjectsPassingTest: will invoke a block for each object in the array. It uses a return value of YES or NO to control whether that object's index is added to the index set that is ultimately returned.
NSIndexSet *indices = [array indexesOfObjectsPassingTest: ^(id object, NSUInteger index, BOOL *stop) { NSRange match = [object rangeOfString: @"badger"]; if (match.location != NSNotFound) { return YES; } else { return NO; } }]; NSLog (@"%@", indices);
This prints:
<NSIndexSet> [number of indexes: 2 (in 2 ranges), indexes: (2 4)]
which corresponds to "badger" and "badgerific."