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:

^​B​O​O​L​ ​(​i​d​ ​o​b​j​e​c​t​,​ ​N​S​U​I​n​t​e​g​e​r​ ​i​n​d​e​x​,​ ​B​O​O​L​ ​*​s​t​o​p​)​ ​{​ ​r​e​t​u​r​n​ ​Y​E​S​;​ ​}​

But you can reduce it a bit because the return type will be inferred:

^​(​i​d​ ​o​b​j​e​c​t​,​ ​N​S​U​I​n​t​e​g​e​r​ ​i​n​d​e​x​,​ ​B​O​O​L​ ​*​s​t​o​p​)​ ​{​ ​r​e​t​u​r​n​ ​Y​E​S​;​ ​}​

A block that takes no arguments and returns no value can be drastically reduced:

^​v​o​i​d​ ...

Get Advanced Mac OS X Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.