Swift中的for循环

前言

任何语言中最常用的就是for循环了 但是Swift的for循环语法一直在变

基本遍历

1
2
3
4
5
6
7
8
9
//0到9
for i in (0..<10) {
print(i)
}

//0到10
for i in (0...10) {
print(i)
}

反向遍历

1
2
3
for i in (0..<10).reversed() {
print(i)
}

数组遍历

1
2
3
for item in list {
print(item)
}

数组遍历 获取索引

1
2
3
for (index, element) in list.enumerated() {
print("Item \(index): \(element)")
}

循环过滤

1
2
3
4
5
//swift闭包可以省略参数且用$0匿名,第二个参数则用$1,以此类推
for i in (1...10).filter({ $0 % 2 == 0}) {
print(i)
//输出结果为1-10之间的偶数
}

遍历字典

1
2
3
4
5
6
7
8
9
// 定义并实例化字典
var dict = [String: AnyObject]()
dict["name"] = "zhangsan" as AnyObject
dict["age"] = 18 as AnyObject

// 遍历字典(k, v可以随便写)
for (k, v) in dict {
print("\(k) -- \(v)")
}