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一致的風(fēng)格
var a = 10
var b = 20
let c = a > b ? a : b
print(c)
適當(dāng)?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:首先判斷 - 代碼中仍然需要使用`!`強行解包 但是不會造成crash
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>當(dāng)判斷需要增加條件的時候,若使用if的嵌套 ,則會使代碼復(fù)雜冗余
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 子句沒有智能提示
-
多個可選項判斷
//可以使用`,`同時判斷多個可選項是否為空
let tName:String? = "zhangsan"
let tNO:Int? = 29
if let name = tName {
if let no = tNo {
print("姓名:" + name + "學(xué)號:" + String(no))
}
}
if let name = tName, let no = tNo {
print("姓名:" + name + "學(xué)號:" + String(no))
}
判斷之后對變量需要修改
let tName:String? = "張三"
let tNo:Int? = 19
if var name = tName, no = tNo {
name = "李四"
no = 1
print("姓名:" + name + "學(xué)號:" + String(no))
}
guard
- guard 是與
if let相反的語法, Swift 2.0 推出
let tName:String? = "zhangsan"
let tNo:Int? = 9
guard let name = tName else {
print("name為空")
retuen
}
guard let no = tNo else {
print("no為空")
return
}
//代碼如果能執(zhí)行至此, name & no 都肯定是有值的
print(name)
print(no)
- 在程序編寫時, 條件檢測之后的代碼是相對復(fù)雜的
- 使用 guard 的好處
- 能夠判斷每一個值
- 在真正的代碼邏輯部分,省略了一層嵌套
switch
- switch 不再局限于整數(shù)
- switch 可以針對任意數(shù)據(jù)類型進行判斷
- 不再需要 break
- 每一個 case 后面必須有可以執(zhí)行的語句
- 要保證處理所有可能的情況, 不然編譯器直接報錯, 不處理的條件可以放在 default 分支中
- 每個 case 中定義的變量僅在 當(dāng)前 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 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("其他")
}