swich 语句
选择情况比较多的时候,一个情况可以设定为一个 case
比如判断今天是星期几
var week = 6
switch week {
var week = 6
switch week {
case 1:
print("星期一")
case 2:
print("星期二")
case 3:
print("星期三")
case 4:
print("星期四")
case 5:
print("星期五")
case 6:
print("星期六")
case 7:
print("星期日")
default:
print("qingshuruzhengquede")
}
匹配条件,有多种方式的匹配
// 字符串的模式匹配
// 满足哪个就执行哪个 case 中的语句,在 oc 中是不可以的
var name = "ls"
switch name {
case "zs":
print("zhangsan")
//break 是隐形默认添加的,不用手动写
// break
case "ls":
print("lisi")
// break
default:
print("qita")
}
// 字符串的模式匹配
// 满足哪个就执行哪个 case 中的语句,在 oc 中是不可以的
var name = "ls"
switch name {
case "zs":
print("zhangsan")
// break
case "ls":
print("lisi")
// break
default:
print("qita")
}
//区间匹配
var num = 80
switch num {
case 0:
print("缺考")
case 0 ..< 60:
print("及格")
case 60..<80:
print("良好")
case 80..<100:
print("优秀")
default:
print("未知情况")
}
元组在switch 中的运用
let image = UIImageView(image: UIImage(named: "zuobiaotu"))
let pointA = (x:10,y:-10)
switch pointA {
case (0,0):
print("该点在原点")
case (0,_):
print("该点在x轴")
case (_,0):
print("该点在y轴")
case (0...Int.max,0...Int.max):
print("该点在第一象限")
case (-Int.max...0,0):
print("该点在第二象限")
case (-Int.max...0,-Int.max...0):
print("该点在第三象限")
case (0...Int.max,-Int.max...0):
print("该点在第四象限")
default:
print("未知情况")
}
//swith 中使用值绑定 与 where 语句
// 可以增加一个 where 的判断语句
let point2 = (2,2)
switch point2 {
case (let x,let y) where (x == y ):
print("point 在 x=y 的方程线上")
case (let x,let y) where (x == -y ):
print("point 在 x=-y 的方程线上")
default:
print("其他情况")
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。