非零即真
概念true
/ false
()
可以省略{}
不能省略
func demo() {
let a = 10
if a > 1 { print("你是猪") } else { print("你是驴") }
|
let score = 75
if score >= 90 && score <= 100 {
print("A") } else if score >= 80 { print("B") } else if score >= 70 { print("C") } else if score >= 60 { print("D") } else { print("E") }
|
// 在OC中
if (1 < 2) printf("我被打印了\n");
// 在 Swift 中
if (1 < 2) { print("我被打印了") }
|
nil
,而一旦为 nil
则不允许参与计算nil
let url = NSURL(string: "http://www.baidu.com") //: 方法1: 强行解包 - 缺陷,如果 url 为空,运行时会崩溃 let request = NSURLRequest(URL: url!) //: 方法2: 首先判断 - 代码中仍然需要使用 `!` 强行解包 if url != nil { let request = NSURLRequest(URL: url!) } //: 方法3: 使用 `if let`,这种方式,表明一旦进入 if 分支,u 就不在是可选项 if let u = url where u.host == "www.baidu.com" { let request = NSURLRequest(URL: u) }
|
func demo3() {
let ulstring = "http://www.douniwan.com?" // if let判断是否为空,为空就不在执行,不为空,就赋值程序继续往下走 if let url = NSURL(string: ulstring) { print(url) // 程序运行到这里,一定有值 let request = NSURLRequest(URL: url) }
}
|
//: 1> 初学 swift 一不小心就会让 if 的嵌套层次很深,让代码变得很丑陋
if let u = url { if u.host == "www.baidu.com" { let request = NSURLRequest(URL: u) } } //: 2> 使用 where 关键字, if let u = url where u.host == "www.baidu.com" { let request = NSURLRequest(URL: u) }
|
if let
不能与使用 &&
、||
等条件判断where
子句where
子句没有智能提示
//: 3> 可以使用 `,` 同时判断多个可选项是否为空
let oName: String? = "张三" let oNo: Int? = 100 if let name = oName { if let no = oNo { print("姓名:" + name + " 学号: " + String(no)) } } if let name = oName, let no = oNo { print("姓名:" + name + " 学号: " + String(no)) }
|
let oName: String? = "张三"
let oNum: Int? = 18 if var name = oName, num = oNum { name = "李四" num = 1 print(name, num) }
|
guard
是与 if let
相反的语法,Swift 2.0 推出的
func demo4() {
let ulstring = "http//www.baidu.com?主" // 在这里guard let 会阻止一切为空的数值 guard let url = NSURL(string: ulstring) else{ return }
//确保代码执行到这里,一定有值
print(url)
}
|
// ??
// 所有可选项都不可以参与运算 // ??强制快速排空 后面的数值是一个默认值 如果为空,就会选用后面的值参与运算 // 小括号括起来 是因为-1的优先级比较高 ,会先运算-1 + 10 在西安与前面的运算 // let没有默认值,因此会报错
func demo5() {
var a:Int? = 10
print((a ?? -1) + 10) }
|
switch
不再局限于整数switch
可以针对任意数据类型
进行判断break
case
后面必须有可以执行的语句default
分支中case
中定义的变量仅在当前 case
中有效,而 OC 中需要使用 {}
// switch
func demo() {
let gf = "杨幂" switch gf{ case "杨幂","范冰冰": let str = "羡慕嫉妒恨" print("富二代") case "刘诗诗": print("大叔") case "凤姐": print("呵呵") default: print("单身狗") } }
|
where
子句
let point = CGPoint(x: 10, y: 10)
switch point { case let p where p.x == 0 && p.y == 0: print("中心点") case let p where p.x == 0: print("Y轴") case let p where p.y == 0: print("X轴") case let p where abs(p.x) == abs(p.y): print("对角线") default: print("其他") }
|
switch score {
case _ where score > 80: print("优") case _ where score > 60: print("及格") default: print("其他") }
|
原文:http://www.cnblogs.com/mrhanlong/p/4944999.html