Format Strings

It's hard to play with types without the ability to print them to the console, but in order to do so, we need to understand format strings. Back in the Hello World! program, we used NSLog to print out a fixed string:

NSLog(@"Hello World!");

But now we want to print out variables as well. Unfortunately, we need to tell NSLog the type of the variable as well. Each type has an associated token of the form %<x> where x is determined by the type of the variable.

Integers
%i
Decimals (floats)
%f
NSString
%@
NSString *name = @"The Tempest";
float height = 1.75;
int age = 42;
NSLog(@"%@ is my favorite Shakepear play", name);
NSLog(@"You must be at least %f meteres tall to ride this ride", height);
NSLog(@"That person over there is %i years old", age);

In each case, the token %<x> was replaced by the value of the variable. We can even insert multiple values into a single format string.

NSLog(@"I am casting a performance of %@. I need to find an actress over %i who
is at least %f meteres tall.", name, age, height);

Notice that the variables are specified in the same order as the tokens they are to replace.

Exercises

  1. Print out a variable of each type to the console.
  2. Find out what happens when you use the incorrect token for a variable.