swift 学习笔记(16)-switch 语句

前端之家收集整理的这篇文章主要介绍了swift 学习笔记(16)-switch 语句前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

swich 语句
选择情况比较多的时候,一个情况可以设定为一个 case

比如判断今天是星期几

  1. var week = 6
  2. switch week {
  3. var week = 6
  4. switch week {
  5. case 1:
  6. print("星期一")
  7. case 2:
  8. print("星期二")
  9. case 3:
  10. print("星期三")
  11. case 4:
  12. print("星期四")
  13. case 5:
  14. print("星期五")
  15. case 6:
  16. print("星期六")
  17. case 7:
  18. print("星期日")
  19. default:
  20. print("qingshuruzhengquede")
  21. }

匹配条件,有多种方式的匹配

  1. // 字符串的模式匹配
  2. // 满足哪个就执行哪个 case 中的语句,在 oc 中是不可以的
  3.  
  4. var name = "ls"
  5. switch name {
  6. case "zs":
  7. print("zhangsan")
  8. //break 是隐形默认添加的,不用手动写
  9. // break
  10. case "ls":
  11. print("lisi")
  12. // break
  13.  
  14. default:
  15. print("qita")
  16. }
  1. // 字符串的模式匹配
  2. // 满足哪个就执行哪个 case 中的语句,在 oc 中是不可以的
  3.  
  4. var name = "ls"
  5. switch name {
  6. case "zs":
  7. print("zhangsan")
  8. // break
  9. case "ls":
  10. print("lisi")
  11. // break
  12.  
  13.  
  14. default:
  15. print("qita")
  16. }
  1. //区间匹配
  2.  
  3. var num = 80
  4. switch num {
  5. case 0:
  6. print("缺考")
  7. case 0 ..< 60:
  8. print("及格")
  9. case 60..<80:
  10. print("良好")
  11. case 80..<100:
  12. print("优秀")
  13. default:
  14. print("未知情况")
  15. }

元组在switch 中的运用

  1. let image = UIImageView(image: UIImage(named: "zuobiaotu"))
  2. let pointA = (x:10,y:-10)
  3. switch pointA {
  4. case (0,0):
  5. print("该点在原点")
  6. case (0,_):
  7. print("该点在x轴")
  8. case (_,0):
  9. print("该点在y轴")
  10. case (0...Int.max,0...Int.max):
  11. print("该点在第一象限")
  12. case (-Int.max...0,0):
  13. print("该点在第二象限")
  14. case (-Int.max...0,-Int.max...0):
  15. print("该点在第三象限")
  16. case (0...Int.max,-Int.max...0):
  17. print("该点在第四象限")
  18.  
  19. default:
  20. print("未知情况")
  21. }
  1. //swith 中使用值绑定 与 where 语句
  2. // 可以增加一个 where 的判断语句
  3.  
  4. let point2 = (2,2)
  5. switch point2 {
  6. case (let x,let y) where (x == y ):
  7. print("point 在 x=y 的方程线上")
  8. case (let x,let y) where (x == -y ):
  9. print("point 在 x=-y 的方程线上")
  10.  
  11. default:
  12. print("其他情况")
  13. }

猜你在找的Swift相关文章