Swift 基本語法
大體來說,Swift我們需要掌握下面一些常用的基本語法:
我會一步一步整理出來, 今天暫時整理常量和變量,可選項;
1. 常量 & 變量
2. 可選項
3. 控制流
if
三目
if let
guard
switch
4. 字符串
5. 循環
6. 集合
6.1 數組
6.2 集合
接上期:
Swift基本語法(01) --- 常量 & 變量 & 可選項
三 .控制流
1. if
**
Swift 中沒有 C 語言中的非零即真概念
在邏輯判斷時必須顯示地指明具體的判斷條件 true / false
if 語句條件的 () 可以省略
但是 {} 不能省略**
let num = 200
if num < 10 {
print("比 10 小")
} else if num > 100 {
print("比 100 大")
} else {
print("10 ~ 100 之間的數字")
}
2. 三目運算
**Swift 中的 三目 運算保持了和 OC 一致的風格 **
var a = 10
var b = 20
let c = a > b ? a : b
print(c)
適當地運用三目,能夠讓代碼寫得更加簡潔
3.可選項判斷
**由于可選項的內容可能為 nil,而一旦為 nil 則不允許參與計算
因此在實際開發中,經常需要判斷可選項的內容是否為 nil **
3.1 單個可選項判斷
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)
}
3.2 可選項條件判斷
//: 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.3 多個可選項判斷
// : 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))
}
3.4 判斷之后對變量需要修改
let oName: String? = "張三"
let oNum: Int? = 18
if var name = oName, num = oNum {
name = "李四"
num = 1
print(name, num)
}
4. 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
}
// 代碼執行至此,name & num 都是有值的
print(name)
print(num)
在程序編寫時,條件檢測之后的代碼相對是比較復雜的
使用 guard 的好處
能夠判斷每一個值
在真正的代碼邏輯部分,省略了一層嵌套
5. switch
switch 不再局限于整數
switch 可以針對任意數據類型進行判斷
不再需要 break
每一個 case后面必須有可以執行的語句
要保證處理所有可能的情況,不然編譯器直接報錯,不處理的條件可以放在 default 分支中
每一個 case 中定義的變量僅在當前 case 中有效,而 OC 中需要使用 {}
let score = "優"
switch score {
case "優":
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("優")
case _ where score > 60: print("及格")
default: print("其他")
}