if
- Swift 中沒有 C 語言中的
非零即真
概念 - 在邏輯判斷時必須顯示地指明具體的判斷條件
true
/false
- if 語句條件的
()
可以省略 - 但是
{}
不能省略
let num = 200
if num < 10 {
print("比 10 小")
} else if num > 100 {
print("比 100 大")
} else {
print("10 ~ 100 之間的數(shù)字")
}
三目運算
- Swift 中的
三目
運算保持了和 OC 一致的風格
var a = 10
var b = 20
let c = a > b ? a : b
print(c)
適當?shù)剡\用三目躺率,能夠讓代碼寫得更加簡潔
可選項判斷
- 由于可選項的內(nèi)容可能為
nil
,而一旦為nil
則不允許參與計算 - 因此在實際開發(fā)中,經(jīng)常需要判斷可選項的內(nèi)容是否為
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)
}
可選項條件判斷
//: 1> 初學 swift 一不小心就會讓 if 的嵌套層次很深洲敢,讓代碼變得很丑陋
if let u = url {
if u.host == "www.baidu.com" {
let request = NSURLRequest(URL: u)
}
}
//: 2> 使用 where 關(guān)鍵字,
if let u = url where u.host == "www.baidu.com" {
let request = NSURLRequest(URL: u)
}
- 小結(jié)
-
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
-
guard
是與if let
相反的語法,Swift 2.0 推出的
let oName: String? = "張三"
let oNum: Int? = 18
guard let name = oName else {
print("name 為空")
return
}
guard let num = oNum else {
print("num 為空")
return
}
// 代碼執(zhí)行至此渗常,name & num 都是有值的
print(name)
print(num)
- 在程序編寫時壮不,條件檢測之后的代碼相對是比較復(fù)雜的
- 使用 guard 的好處
- 能夠判斷每一個值
- 在真正的代碼邏輯部分,省略了一層嵌套
switch
-
switch
不再局限于整數(shù) -
switch
可以針對任意數(shù)據(jù)類型
進行判斷 - 不再需要
break
- 每一個
case
后面必須有可以執(zhí)行的語句 - 要保證處理所有可能的情況皱碘,不然編譯器直接報錯询一,不處理的條件可以放在
default
分支中 - 每一個
case
中定義的變量僅在當前case
中有效,而 OC 中需要使用{}
let score = "優(yōu)"
switch score {
case "優(yōu)":
let name = "學生"
print(name + "80~100分")
case "良": print("70~80分")
case "中": print("60~70分")
case "差": print("不及格")
default: break
}
- switch 中同樣能夠賦值和使用
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("優(yōu)")
case _ where score > 60: print("及格")
default: print("其他")
}