Swift
中沒有了for-of
循環,大部分遍歷內容都落在了for-in
的身上。
一、基本用法
遍歷數組內容
let array = [1, 2, 3, 4, 5]
for item in array {
print(item)
}
遍歷字符串內容
和下標
for (n, c) in "Swift".enumerated() {
print("\(n): '\(c)'")
}
---console
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"
遍歷數組內容
和下標
let array = [1, 2, 3, 4, 5]
for (i, v) in array.enumerated() {
print("i: \(i); v: \(v)")
}
---console
i: 0; v: 1
i: 1; v: 2
i: 2; v: 3
i: 3; v: 4
i: 4; v: 5
遍歷字典key
和value
let dic = ["k1": "v1", "k2": "v2", "k3": "v3", "k4": "v4"]
for (k, v) in dic {
print("k: \(k); v: \(v)")
}
---console
k: k1; v: v1
k: k4; v: v4
k: k2; v: v2
k: k3; v: v3
二、循環限制
2.1 區間限制
-
...
表示閉區間,如:0...10
,表示0
至10
,并且包含10
-
..<
表示開區間,如:0..<10
,表示0
至9
,不包含10
for i in 0..<10 {
print(i)
}
// 0 1 2 3 4 5 6 7 8 9
for i in 0...10 {
print(i)
}
// 0 1 2 3 4 5 6 7 8 9 10
2.2 stride限制
stride
語法提供了更大的靈活性,滿足不同的遞增條件以和開閉區間的結合。
-
func stride<T>(from start: T, to end: T, by stride: T.Stride)
返回從起始值到結束值(但不包括結束值)的序列,按指定的步長數量遞增。 -
func stride<T>(from start: T, through end: T, by stride: T.Stride)
返回從起始值到結束值(可能包括結束值)的序列,按指定的步長數量逐步遞增。
【提示】如果需要遞減,可以把步長數值設置為負值,但是注意也需要把結束值設置的比起始值小,要不然將沒有結果。
for item in stride(from: 0, to: 10, by: 2) {
print(item, terminator: " ")
}
---console
// 0 2 4 6 8
for item in stride(from: 0, through: 10, by: 2) {
print(item, terminator: " ")
}
---console
// 0 2 4 6 8 10
for countdown in stride(from: 3, through: 1, by: -1) {
print("\(countdown)...")
}
// 3...
// 2...
// 1...
2.3 where限制
where
語句就是添加限制條件使用的,for-in
中當然也可以使用。
let arrayOne = [1, 2, 3, 4, 5]
let dictionary = [1: "v1", 2: "v2"]
for i in arrayOne where dictionary[i] != nil {
print("i: \(i)")
}
---console
i: 1
i: 2