[绍棠] swift for 循环

在swift 4.2  中已经舍弃了传统的C语言的for;;循环,替换成更能符合本身语言特性的新形式。

第一种 for - in

这一种是最常用的,可以遍历所有的集合类。如下:

func testFor(){
    let list = [1,2,3,4];
    for idx in list {
        print("idx =\(idx)");
    }
    let dict = ["a":1,"b":2,"c":3];
    for item in dict {
        print("item = \(item)");
    }
}

在控制台输出如下:

idx =1
idx =2
idx =3
idx =4
item = (key: "a", value: 1)
item = (key: "c", value: 3)
item = (key: "b", value: 2)

当遍历字典的时候,会自动转换成元组,包含了key和value,我们也可以自己来通过写一个元组来接收如下:

    let dict = ["a":1,"b":2,"c":3];
    for (key,value) in dict {
        print("key: \(key) value : \(value) ");
        
    }

还有一种区间遍历如下:

    for idx in 0...3 {
        print("idx =\(idx)");
    }

对于这种遍历是swift一个特性,0...3表示,从0到3包含3,如果是0..<3,是0到3但是不包含3。

还以反向遍历如下:

    
    let list = [1,2,3,4];
    for idx in list.reversed() {
        print("idx =\(idx)");
    }

有时候我们需要知道当前遍历数组的下标,那么我们就可以用下列形式:

    let list = ["A","B","C","D"];
    for item in list.enumerated() {
        print("idx =\(item)");
    }
    
    for (idx,item) in list.enumerated() {
        print("下标:\(idx) 值:\(item)")
    }

第二种,跨步遍历,这个是swift另外一个特性。举个例子:

    for idx in stride(from: 0, to: 10, by: 2) {
        print("idx = \(idx)");
        
    }

这个意思是说从0到10,每隔2个遍历一次,输出的结果是:

扫描二维码关注公众号,回复: 10412318 查看本文章
idx = 0
idx = 2
idx = 4
idx = 6
idx = 8
发布了179 篇原创文章 · 获赞 24 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/happyshaotang2/article/details/103456889