Functions can come in handy in many cases, but let's begin with a particularly useful example that continues with the project of managing parameters. Suppose you have a Swarm file MyParameters.m that sets the values of many parameters. Suppose there are 50 ints and 40 doubles. You may go insane writing methods to get each parameter specifically by name.
There is no need to write specific get methods for each variable because a combination of methods from Swarm and C can be used to create "generic" get functions that will retrieve the values. In the top part of the MyParameters.m file, between the include statements and the implementation statement, the functions are defined thus:
//MyParameters.m [import statements here] id makeProbe (id obj, const char *ivarName) { id probe = [VarProbe createBegin: [obj getZone]]; [probe setProbedClass: [obj getClass]]; [probe setProbedVariable: ivarName]; return [probe createEnd]; } double getDouble (id obj, const char *ivarName) { id probe = makeProbe (obj, ivarName); double ret = [probe probeAsDouble: obj]; [probe drop]; return ret; } int getInt (id obj, const char *ivarName) { id probe = makeProbe (obj, ivarName); int ret = [probe probeAsInt: obj]; [probe drop]; return ret; } @implementation MyParameters [and so forth...] |
These functions are made available to calls in other files by declaring them in the header file, MyParameters.h. The declarations are inserted between the import statements and before the interface declaration.
//MyParameters.h [import statements here] id makeProbe (id obj, const char *ivarName); double getDouble (id obj, const char *ivarName); int getInt (id obj, const char *ivarName); @interface MyArguments: Arguments_c [And so forth...] |
In any file that includes MyParameters.h, one can retrieve the value of a parameter by using the getInt and getDouble functions. For example, if there is an instance variable defined in MyParameters called maxHeat, it can be retrieved by the following call to the function:
getInt(arguments, "maxHeat"); |
This call is made against the object called arguments because, as mentioned in the previous section, the instantiation of MyParameters is named arguments inside the Swarm kernel.