📅  最后修改于: 2023-12-03 14:47:47.494000             🧑  作者: Mango
在 Swift 中 for-in
循环是一种非常方便的遍历集合元素的方法。
let numbers = [1, 2, 3, 4, 5]
for number in numbers {
print(number)
}
输出:
1
2
3
4
5
let dictionary = ["A": 1, "B": 2, "C": 3]
for (key, value) in dictionary {
print("\(key): \(value)")
}
输出:
A: 1
B: 2
C: 3
for i in 1...5 {
print(i)
}
输出:
1
2
3
4
5
let str = "Swift"
for character in str {
print(character)
}
输出:
S
w
i
f
t
let fruits = ["Apple", "Banana", "Orange"]
for (index, fruit) in fruits.enumerated() {
print("Index: \(index), value: \(fruit)")
}
输出:
Index: 0, value: Apple
Index: 1, value: Banana
Index: 2, value: Orange
let optionalNumber: Int? = nil
for number in optionalNumber ?? 0...5 {
print(number)
}
输出:
0
1
2
3
4
5
以上是 Swift 中 for-in
循环的常用用法。除此之外,for-in
循环还有很多用法,可以根据具体需求灵活使用。