swift 中數(shù)組遍歷的7種寫法
列舉如下, <最后一種是錯(cuò)誤的寫法>
let array = ["元素1","元素2","元素3"]
1. 區(qū)間遍歷
print("方法1************")
for i in 0..<array.count{
print(array[i])
}
2. for in 遍歷
print("方法2************")
for s in array{
print(s)
}
3.元組遍歷
print("方法3************")
for s in array.enumerated(){
print(s.offset, s.element)
}
4.元組
print("方法4************")
for (index, element) in array.enumerated(){
print(index,element)
}
5. 元組遍歷
print("方法5************")
for s in array.enumerated(){
print(s.0,s.1)
}
6. 反序遍歷
print("方法6 反序************")
for s in array.enumerated().reversed(){
print(s.0,s.1)
}
7. 反序遍歷
print("方法7 反序************")
for s in array.reversed(){
print(s)
}
8. ****錯(cuò)誤寫法 , 序號(hào)和元素沒有一一對(duì)應(yīng)****
**** /*************** 錯(cuò)誤寫法**************/ ****
print("****反序 錯(cuò)誤寫法********")
for s in array.reversed().enumerated(){
print(s.0,s.1)
}
// 打印結(jié)果如下
方法1************
元素1
元素2
元素3
方法2************
元素1
元素2
元素3
方法3************
0 元素1
1 元素2
2 元素3
方法4************
0 元素1
1 元素2
2 元素3
方法5************
0 元素1
1 元素2
2 元素3
方法6 反序************
2 元素3
1 元素2
0 元素1
方法7 反序************
元素3
元素2
元素1
****反序 錯(cuò)誤寫法********
0 元素3
1 元素2
2 元素1