Swift中遍历方法for in 和 forEach的区别

作者: langkee | 来源:发表于2017-05-04 14:44 被阅读2741次

    前言

    在swift中,我们经常会用到的两种快速遍历的方法,一种是最常见也是最常用的for ... in ..., 另外一种也是不同于Objective-C的forEach。那么,两者的使用有什么区别呢?今天,让我们来聊一聊swift中遍历方法的那些事。

    for in 与 forEach

    同类型的泛型集合
    • for in
    let array = ["1", "2", "3", "4", "5"]
    for element in array {
        print(element)
    }
    
    打印结果: 1, 2, 3, 4, 5
    
    • forEach
    let array = ["1", "2", "3", "4", "5"]
    array.forEach { (element) in
        print(element)
    }
    
    打印结果: 1, 2, 3, 4, 5
    

    在集合的元素类型相同(比如上面的数组是String类型)的情况下,两者遍历效果相同,方便、敏捷,我们可以随意选用。

    不同类型元素的集合
    • for in
    let array = [1, 2, 3, "cat", "rabbit"] as [Any]            // as [Any]是swift 3的语法要求,因为数组中有两种不同类型的元素,分别是:Int 、String, 所以需要转化成 [Any]类型
    for element in array {
        print(element)
    }
    
    打印结果:1, 2, 3, cat, rabbit
    
    • forEach
    let array = [1, 2, 3, "cat", "rabbit"] as [Any]
    array.forEach { (element) in
        print(element)
    }
    
    打印结果:1, 2, 3, cat, rabbit
    

    在集合的元素类型不相同(比如上面的数组是IntString类型)的情况下,两者遍历效果相同,方便、敏捷,我们可以也随意选用。

    return关键字
    • for in
    let array = ["1", "2", "3", "4", "5"]
    for element in array {
        if element == "3" {
            return
        }
        print(element)
    }
    print("Hello World")
    
    打印结果:1, 2
    
    • forEach
    let array = ["1", "2", "3", "4", "5"]
    array.forEach { (element) in
        if element == "3" {
            return
        }
        print(element)
    }
    print("Hello World")
    
    打印结果:1, 2, 4, 5, Hello World
    

    在使用return关键字的时候,很明显,for in中是当符合当前执行语句时,程序直接终止到此并返回, 比如上面的元素 "4""5""Hello World" 没有被执行;而forEach中是当符合当前执行语句时,程序跳过本次判断继续执行, 比如上面的元素"4""5""Hello World"被执行。

    continue关键字
    • for in
    let array = ["1", "2", "3", "4", "5"]
    for element in array {
        if element == "3" {
            continue
        }
        print("element is \(element)")
    }
    print("Test \"continue\"")
    
    打印结果:
    element is 1
    element is 2
    element is 4
    element is 5
    Test "continue"
    
    • forEach
    let array = ["1", "2", "3", "4", "5"]
    array.forEach { (element) in
        if element == "3" {
            continue
        }
        print(element)
    }
    print("Test \"continue\"")
    
    错误: 程序根本不能执行
    error:continue is only allowed inside a loop
    

    在使用continue关键字的时候,for in可以正常遍历并且执行,而且 continue的作用是跳出本次循环,不影响后面的执行; 而在 forEach中,swift是不允许这样执行的,报错的原因是说 continue只允许出现在循环语句中,也就是说不能使用在 forEachclosure中。

    break关键字
    • for in
    let array = ["1", "2", "3", "4", "5"]
    for element in array {
        if element == "3" {
            break
        }
        print("element is \(element)")
    }
    print("Test \"continue\"")
    
    打印结果:
    element is 1
    element is 2
    Test "continue"
    
    • forEach
    let array = ["1", "2", "3", "4", "5"]
    array.forEach { (element) in
        if element == "3" {
            break
        }
        print(element)
    }
    print("Test \"continue\"")
    
    错误:程序根本不能执行
    error:Unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do
    

    break关键字中,对于for in来说是可以的,跳出本层循环,也就是for循环,然后继续执行后面的程序; 对于forEach来说,同continue关键字的效果一样,swift不允许这样使用,原因说的是break只能用于循环语句或switch语句,break会退出本层循环语句。

    Apple官方对 forEach 的说明

    下面是Apple的官方文档解释,对forEach遍历方法做了个大致的介绍,有兴趣可以看一下

    /// Calls the given closure on each element in the sequence in the same order
    /// as a `for`-`in` loop.
    ///
    /// The two loops in the following example produce the same output:
    ///
    ///     let numberWords = ["one", "two", "three"]
    ///     for word in numberWords {
    ///         print(word)
    ///     }
    ///     // Prints "one"
    ///     // Prints "two"
    ///     // Prints "three"
    ///
    ///     numberWords.forEach { word in
    ///         print(word)
    ///     }
    ///     // Same as above
    ///
    /// Using the `forEach` method is distinct from a `for`-`in` loop in two
    /// important ways:
    ///
    /// 1. You cannot use a `break` or `continue` statement to exit the current
    ///    call of the `body` closure or skip subsequent calls.
    /// 2. Using the `return` statement in the `body` closure will exit only from
    ///    the current call to `body`, not from any outer scope, and won't skip
    ///    subsequent calls.
    ///
    /// - Parameter body: A closure that takes an element of the sequence as a
    ///   parameter.
    
    

    </br>
    小结:

    • for in 能使用 return、break、continue关键字,forEach不能使用 break、continue关键字
    • for in 和 forEach 在 return关键字 的使用上有着本质的区别
    • 一般情况下,两者都可通用,都方便、敏捷
    • for in 使用范围比 forEach更广

    </br>

    欢迎加入 iOS(swift)开发互助群:QQ群号:558179558, 相互讨论和学习!你想要的答案这里都有...

    相关文章

      网友评论

        本文标题:Swift中遍历方法for in 和 forEach的区别

        本文链接:https://www.haomeiwen.com/subject/mdgrtxtx.html