Block Literal Syntax
This section shows how to write Block literal. The syntax of Block literal is explained with examples. After reading this, you should be able to write Block literals.
First, let’s see how to declare a function in C.
void func(int event) {
printf("buttonId:%d event=%d\n", i, event);
}
which means it is declared by the return type, function name, argument list, and its implementation. Let’s see how a Block literal is written. In previous sections, a Block literal was written in an abbreviated form as
^(int event) {
printf("buttonId:%d event=%d\n", i, event);
}
You can also write it in full as
There are only two differences between this Block literal and a function declaration in C: there is no function name and there is a caret symbol (^).
Block literal has no name for the function. It makes it an anonymous function. The second one means that for Block literal, a ^ (caret) is written just before the return type of the function. It is very probable that you will see this symbol more often from now on because Blocks will become common in OSX and iOS applications.
As confirmation, the following is a BNF of Block literal syntax.1
Block_literal_expression ::= ^ block_decl compound_statement_body
block_decl ::= return_type
block_decl ::= parameter_list
block_decl ::= type_expression
Even if you have no idea about BNF, you might be able to guess what it means. Please seeFigure 4–1.
Figure 4–1. Block literal syntax
The return type is just same as that of a function declaration in C. The parameter list and expressions are also the same. Of course the return type has to match its “return” sentence if there is one. For example, we can use a Block literal as follows.
^int (int count){return count + 1;}
As in the previous example, some items can be omitted. First, you can omit the return type as shown in Figure 4–2.
Figure 4–2. Block literal syntax without return type
When the return type is omitted, the variable type in the return sentence is used instead.When the Block literal doesn’t have a return sentence, “void” is used. When the Block has multiple return sentences, all of their variable types must be the same. When the return type is omitted, it is written as
^(int count){return count + 1;}
In this Block literal, the return type is int because of its return sentence.
__________
1 Wikipedia, “Backus—Naur Form” http://en.wikipedia.org/wiki/Backus-Naur_Form
If the function takes no arguments, the argument list can be omitted as well. The next source code is an example of a Block with no argument.
^void (void){printf("Blocks\n");}
This can be abbreviated as follows.
^{printf("Blocks\n");}
This abbreviated Block literal (Figure 4–3) will prove to be the most familiar form for you.
Figure 4–3. Block literal syntax without return type and argument list