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.
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.