A switch statement tests a variable for equality against a list of values.
The syntax for a switch statement in Objective-C programming language is as follows:
switch(expression){ case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ case ... ... break; case ... ... break; default : /* Optional */ statement(s); }
#import <Foundation/Foundation.h> int main () { char grade = 'B'; switch(grade) { case 'A' : NSLog(@"A!\n" ); break; case 'B' : case 'C' : NSLog(@"B\n" ); break; case 'D' : NSLog(@"D\n" ); break; case 'F' : NSLog(@"F\n" ); break; default : NSLog(@"Invalid grade\n" ); } NSLog(@"Your grade is %c\n", grade ); return 0; }
#import <Foundation/Foundation.h> int main () { int X = 2; switch (X) { case 1: NSLog (@"X = 1"); break; case 2: NSLog (@"X = 2"); break; default: NSLog (@"Default code"); break; } return 0; }
The code above generates the following result.