关于Swift中的forEach(_:)和for-in loop

本文基于Swift5,阅读时间大约须要10min。编程

简介

Swift摒弃了C语言式定义变量、累加变量的for-loop,用for-in取而代之,来遍历集合类型。swift

那什么是forEach(_:)呢?forEach(_:)也是一种遍历方式。虽然都是遍历方式,可是二者仍是有些许的不一样的。下面让咱们来全面了解一下二者。数组

应用场景

for-in

  • 不须要使用索引,只是单纯的遍历集合
let strs = ["first", "second", "third"]
for str in strs {
    print(str) 
}

//first second third
复制代码
  • 须要使用索引
for (index, str) in strs.enumerated() {
    print(index, str)
}
// 0 first
// 1 second
// 2 third
复制代码

forEach(_:)

  • 函数式编程
var arr = ["1", "2", "3"]
arr.map {Int($0)!}.forEach { (num) in
    print(num)
}
// 1 2 3

//假如不使用forEach
let map = arr.map {Int($0)!}
for num in map {
    print(num)
}
复制代码
  • 遍历optional的集合类型
// 若是使用for-in强制解包的话会crash
var optionalStrs:[String]? = nil
for str in optionalStrs! {
    print(str)
}

//使用forEach比较便捷,不会crash
var optionalStrs:[String]? = nil
optionalStrs?.forEach({ (str) in
    print(str)
})
复制代码

区别

  • forEach(_:)是不能使用breakcontinue来退出当前循环的。
  • 在使用return语句的时候,只是退出当前闭包,并不会影响外部的代码块,也不会影响后面循环的调用。
func foreachTextFunc() {
    let strs = ["first", "second", "third"]
    strs.forEach { (str) in
        print(str)
        return;
        print("foreach body")
    }
    print("end")
}

foreachTextFunc()
//first
//second
//third
//end
复制代码

经过上面的代码咱们能够看出,在forEach(_:)添加了return;以后,它仅仅跳过执行print("foreach body"),后面的循环调用和最后的print("end")语句都没有被跳过。安全

Note

若是将上面的return;写成return,它仍是会执行print("foreach body"),具体缘由请点击这里bash

总结

  • 二者的执行顺序是一致的,执行性能没有差异。
  • 当须要使用breakcontinuereturn等控制语句的时候使用for-in
  • 当遍历optional数组的时候,使用forEach(_:)更加安全方便。
  • 当使用函数式编程的时候,使用forEach(_:)

OK,到这里关于forEach(_:)for-in就介绍完了,相信你们都对二者的区别和使用场景都有了清晰地认识。接下来你们能够在项目里尽情的使用它们啦,Enjoy It。闭包

Plus:
若是你们以为本文对你们有一丝帮助,但愿你们点个👍。
若是有任何问题能够在评论区留言
复制代码

参考

相关文章
相关标签/搜索