📜  Swift for-in循环(1)

📅  最后修改于: 2023-12-03 14:47:47.494000             🧑  作者: Mango

Swift for-in循环

在 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 循环还有很多用法,可以根据具体需求灵活使用。