2012年10月17日 星期三

switch case的基本使用

在objectC中如果有需要用到c++ 中的 case用法,可參考下面基本使用例

原始描述
switch(expression or variable)
{
     case value1:
          // Program statement
          // Program statement
          ...
          break;
     case value2:
          // Program statement
          // Program statement
          ...
          break;
     case value3:
          // Program statement
          // Program statement
          ...
          break;
     ...
     case valueN:
          // Program statement
          // Program statement
          ...
          break;
     default:
          // Program statement
          // Program statement
          ...
          break;
}


例子
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return @"鮮花";
            break;
           
        case 1:
            return @"水果";
            break;
           
        default:
            return @"";
            break;
    }
}

另一例
NSString *operator = [[NSString alloc] init];     // We will talk in depth about NSString later on down the road.
 // Assume operator has been initialized to a valid value
 // Valid values for operator are @"+", @"-", @"*", and @"/"

 switch (operator) {
  case @"+":
   NSLog(@"Operator is for addition.");
   break;
  case @"-":
   NSLog(@"Operator is for subtraction.");
   break;
  case @"*":
   NSLog(@"Operator is for multiplication.");
   break;
  case @"/":
   NSLog(@"Operator is for division.");
   break;
  default:
   NSLog(@"Unknown operator.");
   break;
 }
 
以上就相當於
NSString *operator = [[NSString alloc] init];
 // Assume operator has been initialized to a valid value
 // Valid values for operator are @"+", @"-", @"*", and @"/"

 /* Note that NSString actually has a comparison method, and that
    this method of comparison is not guaranteed to work. We are
    overlooking that at the moment for the sake of education. */
 if (operator == @"+")
  NSLog(@"Operator is for addition.");
 else if (operator == @"-")
  NSLog(@"Operator is for subtraction.");
 else if (operator == @"*")
  NSLog(@"Operator is for multiplication.");
 else if (operator == @"/")
  NSLog(@"Operator is for division.");
 else
  NSLog(@"Unknown operator.");   

沒有留言: