- 基本 Objective-C
- Objective-C - 主页
- Objective-C - 概述
- Objective-C - 环境设置
- Objective-C - 程序结构
- Objective-C - 基本语法
- Objective-C - 数据类型
- Objective-C - 变量
- Objective-C - 常量
- Objective-C - 运算符
- Objective-C - 循环
- Objective-C - 决策
- Objective-C - 函数
- Objective-C - 块
- Objective-C - 数字
- Objective-C - 数组
- Objective-C - 指针
- Objective-C - 字符串
- Objective-C - 结构
- Objective-C - 预处理器
- Objective-C - Typedef
- Objective-C - 类型转换
- Objective-C - 日志处理
- Objective-C - 错误处理
- 命令行参数
- 高级 Objective-C
- Objective-C - 类和对象
- Objective-C - 继承
- Objective-C - 多态性
- Objective-C - 数据封装
- Objective-C - 类别
- Objective-C - 摆姿势
- Objective-C - 扩展
- Objective-C - 协议
- Objective-C - 动态绑定
- Objective-C - 复合对象
- Obj-C - 基础框架
- Objective-C - 快速枚举
- Obj-C - 内存管理
- Objective-C 有用资源
- Objective-C - 快速指南
- Objective-C - 有用的资源
- Objective-C - 讨论
Objective-C - switch 语句
switch语句允许测试变量是否与值列表相等。每个值称为一个 case,并且针对每个switch case检查正在打开的变量。
句法
Objective-C 编程语言中switch语句的语法如下 -
switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
以下规则适用于switch语句 -
switch语句中使用的表达式必须具有整型或枚举类型,或者属于类类型,其中该类具有到整型或枚举类型的单个转换函数。
一个 switch 中可以有任意数量的 case 语句。每个案例后面都跟有要比较的值和冒号。
case 的常量表达式必须与 switch 中的变量具有相同的数据类型,并且必须是常量或文字。
当打开的变量等于一个 case 时,该 case 后面的语句将执行,直到到达break语句。
当到达break语句时,switch终止,并且控制流跳转到switch语句之后的下一行。
并非每个案例都需要包含中断。如果没有出现中断,控制流将进入后续案例,直到达到中断为止。
switch语句可以有一个可选的default case,它必须出现在 switch 的末尾。当所有情况都不成立时,可以使用默认情况来执行任务。默认情况下不需要中断。
流程图
例子
#import <Foundation/Foundation.h>
int main () {
/* local variable definition */
char grade = 'B';
switch(grade) {
case 'A' :
NSLog(@"Excellent!\n" );
break;
case 'B' :
case 'C' :
NSLog(@"Well done\n" );
break;
case 'D' :
NSLog(@"You passed\n" );
break;
case 'F' :
NSLog(@"Better try again\n" );
break;
default :
NSLog(@"Invalid grade\n" );
}
NSLog(@"Your grade is %c\n", grade );
return 0;
}
当上面的代码被编译并执行时,它会产生以下结果 -
2013-09-07 22:44:26.928 demo[17555] Well done 2013-09-07 22:44:26.929 demo[17555] Your grade is B
Objective_c_decision_making.htm