Swiftswift

swift 中数组遍历的7种写法

2018-01-06  本文已影响0人  coderLYH

swift 中数组遍历的7种写法

列举如下, <最后一种是错误的写法>

let array = ["元素1","元素2","元素3"]

1. 区间遍历

    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. ****错误写法 , 序号和元素没有一一对应****

  ****  /***************  错误写法**************/    ****
    print("****反序  错误写法********")
    for s in array.reversed().enumerated(){  
        print(s.0,s.1)
    }

// 打印结果如下
方法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
****反序 错误写法********
0 元素3
1 元素2
2 元素1

上一篇 下一篇

猜你喜欢

热点阅读