加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:37:21 所属栏目:百科 来源:网络整理
导读:swich 语句 选择情况比较多的时候,一个情况可以设定为一个 case 比如判断今天是星期几 var week = 6 switch week { var week = 6 switch week { case 1 : print ( "星期一" ) case 2 : print ( "星期二" ) case 3 : print ( "星期三" ) case 4 : print ( "星

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("其他情况")
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读