iOS学习笔记Swift学习IOS

Swift 5.0-for in 与foreach

2019-04-12  本文已影响14人  FlyElephant

Swift中for in和foreach是遍历集合的两种方式,大部分是两种没有差别,不过某些特殊情况下有些不一样。

        let arr: [String] = ["Fly","Elephant","FlyElephant"]
        for item in arr {
            print("\(item)")
        }
        arr.forEach { (item) in
            print("\(item)")
        }

continue 与 break

continue,break只能在for in 循环中使用,foreach如果使用这两个标签会报错。

        let arr: [String] = ["Fly","Elephant","FlyElephant"]
        for item in arr {
            if item == "Fly" {
                continue
            }
            print("\(item)")
        }
        arr.forEach { (item) in
            if item == "Fly" {
                continue
            }
            print("\(item)")
        }

foreach中代码中会报错:

'continue' is only allowed inside a loop
 'break' is only allowed inside a loop

return 语句

for in循环中直接返回不会执行之后的代码,foreach退出当前闭包,但是不会影响迭代的运行。

        let arr: [String] = ["Fly","Elephant","FlyElephant"]
        for item in arr {
            if item == "FlyElephant" {
                return
            }
            print("\(item)")
        }
        print("for in end")
        arr.forEach { (item) in
            if item == "FlyElephant" {
                return
            }
            print("\(item)")
        }
        print("foreach end")

输出结果:

Fly
Elephant

调整一下代码顺序:

        let arr: [String] = ["Fly","Elephant","FlyElephant"]
        arr.forEach { (item) in
            if item == "FlyElephant" {
                return
            }
            print("\(item)")
        }
        print("foreach end")
        for item in arr {
            if item == "FlyElephant" {
                return
            }
            print("\(item)")
        }
        print("for in end")

输出结果如下:

Fly
Elephant
foreach end
Fly
Elephant

参考链接

https://stackoverflow.com/questions/45333177/when-to-use-foreach-instead-of-for-in

上一篇下一篇

猜你喜欢

热点阅读