Functions

Lets say that we want

Declaration

Functions are reuseable procedures that may optionally accept arguments and return values. In Objective-C, functions must be declared before they are used. A function declaration takes the form

{return type} {function name}({arg1 type} {arg1 name}, {arg2 type} {arg2 name});

For example, to declare a function that computes the distance between two points on a grid, the declaration might look something like

float distance(int x1, int y1, int x2, int y2);

Definition

The actual implementation is called the function definition. While declarations can be in header files or implementation files, definitions must be in implementation files. The definition will look exactly like the declaration, except that instead of a trailing semicolon, there will be brackets containing the body of the function.

float distance(int x1, int y1, int x2, int y2) {
  return sqrt( (x1 - x2)^2 + (y1 - y2)^2 );
}

Note the use of the keyword return to return a value. As soon as the return is reached, the function will end, regardless of if there is any code still remaining.

Sometimes a function does not need to return a value, instead just performing some task. In that case, there is the keyword void which takes the place of the return value.

void sayHello(NSString *name) {
  NSLog(@"Hello %@", name);
}

Exercises

  1. Write a function that takes an integer and a string as arguments and prints them out in a nice formatted way.