let y = 10 if y > 0 { print("y > 0") } else { print("y <= 0") }
二、switch 分支语句
基本用法跟OC一致
不同:
switch后可以不跟()
case后可以不跟break(默认会有break)
例子:
let sex = 0 switch sex { case 0 : print("男") case 1 : print("女") default : print("泰国来的") }
补充一: 一个case判断中可以判断多个值,多个值以,隔开
let sex1 = 0 switch sex1 { case 0, 1: print("正常人") default: print("泰国来的") }
正常人
补充二: fallthrough 关键字可以实现case 穿透
let sex2 = 0 switch sex2 { case 0: print("正常人0") fallthrough case 1: print("正常人1") default: print("其他") }
正常人0
正常人1
switch 特殊用法一:支持浮点型
let PI = 3.14 switch PI { case 3.14: print("π") default: print("not π") }
switch 特殊用法二:支持字符串类型
let m = 5 let n = 10 var result = 0 let opration = "+" switch opration { case "+": result = m + n case "-": result = m - n case "*": result = m * n case "/": result = m / n default: result = 0 }
print(result)
15
switch 特殊用法二:switch支持区间判断
swift中的区间常见有两种
开区间:0..<10 表示:0~9,不包括10
闭区间:0...10 表示:0~10
let score = 80 switch score { case 0..<60: print("不及格") case 60..<80: print("及格") case 80..<90: print("良好") case 90..<100: print("优秀") default: print("满分") }