IOS Swift基础之switch用法详解
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不能省略
letname="yangqiangyu"
switchname{
case"yangqiangyu","yqy":
print("Thisismyname")
default:
print("Thisisnotmyname");
}
//"Thisismyname\n"
2、case条件里用范围表达式
letscore=90;
switchscore{
case0:
print("yougotanegg")
case1..<60:
print("youfailed")
case60:
print("Justpassed")
case61..<80:
print("Justsoso")
case80..<90:
print("Good")
case90..<100:
print("Great")
case100:
print("Perfect!")
default:
print("Error")
}
//输出结果:"Great\n"
3、switch使用元组
letpoint:(x:Int,y:Int)=(x:1,y:1)
switchpoint{
case(0,0):
print("It'saorigin")
case(_,0)://忽略point中的x值
print("It'sonx-axis.")
case(0,_)://忽略point中的y值
print("It'sony-axis")
default:
print("It'sjustanordinarypoint")
break
}
//输出结果:
"It'sjustanordinarypoint\n"
4.switch中的case中需要使用元组中的值
letpoint2=(8,0)
switchpoint2{
case(0,0):
print("It'saorigin")
case(letx,0)://赋值给x
print("It'sonx-axis.")
print("Thexvalueis\(x)")
case(0,lety)://赋值给y
print("It'sony-axis")
print("Theyvalueis\(y)")
case(letx,lety):
print("Thexvalueis\(x)")
print("Theyvalueis\(y)")
}
//输出结果:
"It'sonx-axis.\n"
"Thexvalueis8\n"
5.fallthrough使用
letscore=90;
switchscore{
case0:
print("yougotanegg")
case1..<60:
print("youfailed")
case60:
print("Justpassed")
case61..<80:
print("Justsoso")
case80..<90:
print("Good")
case90..<100:
print("Great")
fallthrough
case100:
print("Perfect!")
default:
print("Error")
}
//输出
"Great\n"
"Perfect!\n"
总结
可以发现,Swift中的switch更加灵活和简洁,使用switch可以方便的处理很多操作。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!