大佬教程收集整理的这篇文章主要介绍了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不能省略
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条件里用范围表达式
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使用元组
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中需要使用元组中的值
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使用
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"
可以发现,Swift中的switch更加灵活和简洁,使用switch可以方便的处理很多操作。
以上是大佬教程为你收集整理的Swift之旅 switch用法全部内容,希望文章能够帮你解决Swift之旅 switch用法所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。