IOS Swift基础之switch用法详解
概述
Swift中的switch语句与Java等语言中的switch有很大的相似点,但是也有不同的地方,并且更加灵活。
Swift中switch的case语句中不需要添加break
Swift中需要考虑所有情况,default是必要的。
case分支可以添加多个条件,用,分割
case不局限与常量,可以使使用范围
switch里可以使用元组
switch默认不需要添加break,执行一个case之后就跳出语句,如果想要继续下面的语句可以使用fallthrough,但是fallthrough是直接进入下一个case的语句,不会进行case的判断。感觉这里好坑。
实例代码
1、不需要break,case里多个值用,分割。default不能省略
?
1
2
3
4
5
6
7
8
9
10
11
|
let name = "yangqiangyu"
switch name{
case "yangqiangyu" , "yqy" :
print( "This is my name" )
default :
print( "This is not my name" );
}
//"This is my name\\n"
|
2、case条件里用范围表达式
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
let score = 90;
switch score{
case 0:
print( "you got an egg" )
case 1..<60:
print( "you failed" )
case 60:
print( "Just passed" )
case 61..<80:
print( "Just so so" )
case 80..<90:
print( "Good" )
case 90..<100:
print( "Great" )
case 100:
print( "Perfect!" )
default :
print( "Error" )
}
//输出结果:"Great\\n"
|
3、switch使用元组
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
let point:(x:Int,y:Int) = (x:1,y:1)
switch point{
case (0,0):
print( "It's a origin" )
case (_,0): //忽略point中的x值
print( "It's on x-axis." )
case (0,_): //忽略point中的y值
print( "It's on y-axis" )
default :
print( "It's just an ordinary point" )
break
}
//输出结果:
"It's just an ordinary point\\n"
|
4.switch中的case中需要使用元组中的值
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
let point2 = (8,0)
switch point2{
case (0,0):
print( "It's a origin" )
case (let x,0): //赋值给x
print( "It's on x-axis." )
print( "The x value is \\(x)" )
case (0,let y): //赋值给y
print( "It's on y-axis" )
print( "The y value is \\(y)" )
case (let x,let y):
print( "The x value is \\(x)" )
print( "The y value is \\(y)" )
}
//输出结果:
"It's on x-axis.\\n"
"The x value is 8\\n"
|
5.fallthrough使用
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
let score = 90;
switch score{
case 0:
print( "you got an egg" )
case 1..<60:
print( "you failed" )
case 60:
print( "Just passed" )
case 61..<80:
print( "Just so so" )
case 80..<90:
print( "Good" )
case 90..<100:
print( "Great" )
fallthrough
case 100:
print( "Perfect!" )
default :
print( "Error" )
}
//输出
"Great\\n"
"Perfect!\\n"
|
相关文章
猜你喜欢
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
laravel validate 设置为中文的例子(验证提示为中文)
2025-05-27 88 -
2025-05-24 77
-
2025-05-25 91
-
Java中StringUtils工具类进行String为空的判断解析
2025-05-27 73 -
2025-05-29 61
热门评论