本文共 2390 字,大约阅读时间需要 7 分钟。
和OC中if语句有一定的区别
()
{}
阔起来案例一
let a = 10// 错误写法://if a {// print("a")//}// 正确写法if a > 9 { print(a)}
let score = 87if score < 60 { print("不及格")} else if score <= 70 { print("及格")} else if score <= 80 { print("良好")} else if score <= 90 { print("优秀")} else { print("完美")}
// 这个是可选类型,因为只有声明成可选类型后,才可以判断是否为空// 可选类型会在后续讲解,可先了解即可let view : UIView? = UIView()// 判断如果view有值,则设置背景// 错误写法//if view {// view.backgroundColor = UIColor.red//}if view != nil { view!.backgroundColor = UIColor.red}
var a = 10var b = 50var result = a > b ? a : bprint(result)
guard 条件表达式 else { // 条换语句 break}语句组
var age = 18func online(age : Int) -> Void { guard age >= 18 else { print("回家去") return } print("可以上网")}online(age)
基本用法和OC用法一致
不同之处:
例子
let sex = 0switch sex { case 0 : print("男") case 1 : print("女") default : print("其他")}
let sex = 0switch sex { case 0, 1: print("正常人") default: print("其他")}
let sex = 0switch sex { case 0: fallthrough case 1: print("正常人") default: print("其他")}
let f = 3.14switch f { case 3.14: print("π") default: print("not π")}
let m = 5let n = 10var result = 0let opration = "+"switch opration { case "+": result = m + n case "-": result = m - n case "*": result = m * n case "/": result = m / n default: result = 0}print(result)
let score = 88switch score { case 0..<60: print("不及格") case 60..<80: print("几个") case 80..<90: print("良好") case 90..<100: print("优秀") default: print("满分")}
转载地址:http://sfall.baihongyu.com/