Control structures, loops and blocks

Blocks of program code can be accessed like objects. They can be passed as parameters to messages, or, receive messages with optional parameters and thus become executed.

A simple example for conditional block execution:

(3 > 2) ifTrue: [ res := 'BIGGER' ] ifFalse: [ res := 'smaller' ].

The first part ``(3 > 2)'' is evaluated to a boolean value, which then receives the message ``ifTrue:ifFalse:'' with the two blocks passed as parameters. An object of class boolean is executing the first block if itself evaluates to true, otherwise it executes the second block. The blocks do not receive any values.

We define blocks by putting the code between ``['' and ``]''. At the beginning of the block we state a list of the receiving, local variables for the parameters, each prefixed with a colon (``:arg1''). Local variable declaration has to be separated from the block's code by a ``|''.

Example: Entries in NSArray(9.3) lists are accessed by their indexes.

theElement := myArray objectAtIndex: 2.     " access third element, start counting at 0 (zero) "
0 to: (myArray count) - 1 do: [ :idx |     " counting from 0 to length-1 executes block on every number, which is received in idx "
    theElement := myArray objectAtIndex: idx.     " get element at index given by the local variable idx "
].

NSSet (9.4) lists are accessed by qualitative means.

Example:

(theSet containsObject: myObj) ifTrue: [ Transcript showLine: 'yeah, have it here!' ].

Or, by enumerating all the elements it contains.

Example:

(theSet allObjects) do: [ :elem | Transcript showLine: elem description ].

Same holds for NSDictionary (9.5). We can access all the values it contains, all the keys, or, a single object for a key:

(theDictionary allKeys) do: [ :key | Transcript showLine: key description ].

(theDictionary allValues) do: [ :value | Transcript showLine: value description ].

aValue := theDictionary objectForKey: 'I am a key' .     " retrieve value or nil "
(aValue notNil) ifTrue: [ res := 'YES' ] ifFalse: [ res := 'NO' ].     " test for valid value "

moltalk@moltalk.org      version of this document: V3.0