美文网首页
Swift_遍历方法for in 和 array.forEach

Swift_遍历方法for in 和 array.forEach

作者: Eyes_cc | 来源:发表于2020-03-16 14:41 被阅读0次
【总】一般情况下,两者都可通用,都方便、敏捷。但for in 使用范围比array.forEach更广。

1、同是遍历:都可通用
for..in..

let array = ["1", "2", "3", "4", "5"]
for element in array {
    print(element)
}
打印结果: 1, 2, 3, 4, 5

array.forEach

let array = ["1", "2", "3", "4", "5"]
array.forEach { (element) in
    print(element)
}
array.forEach { element in
    print(element)
}
array.forEach { 
    print($0)
}
打印结果: 1, 2, 3, 4, 5

2、return关键字在其中的不同
for..in..

let array = ["1", "2", "3", "4", "5"]
for element in array {
    if element == "3" {
        return
    }
    print(element)
}
打印结果:1, 2, 
for in中是当符合当前执行语句时,程序直接终止到此并返回,

array.forEach

let array = ["1", "2", "3", "4", "5"]
array.forEach { (element) in
    if element == "3" {
        return
    }
    print(element)
}
打印结果:1, 2, 4, 5, 省略了“3”,
而forEach中是当符合当前执行语句时,程序跳过本次判断继续执行, 

3、continue关键字在其中的不同, 不能在array.forEach中使用
for..in..

let array = ["1", "2", "3", "4", "5"]
for element in array {
    if element == "3" {
        continue
    }
    print("element is \(element)")
}
打印结果:
element is 1
element is 2
element is 4
element is 5

array.forEach

不能使用continue关键字
continue只允许出现在循环语句中。
对于for in可以正常遍历并且执行,而且 continue的作用是跳出本次循环,继续后面的执行
对于array.forEach来说,不能使用。

4、break关键字在其中的不同, 不能在array.forEach中使用
for..in..

let array = ["1", "2", "3", "4", "5"]
for element in array {
    if element == "3" {
        break
    }
    print("element is \(element)")
}
打印结果:
element is 1
element is 2

array.forEach

不能使用break关键字
break只能用于循环语句或switch语句
对于for in来说是可以的,break关键字跳出最外层。
对于array.forEach来说,不能使用。

扩展

可以使用enumerated()方法 例如:
Array.enumerated().forEach { (offset, element) in
………………//offset就是下标 element是数组内对象
}
另外map、filter等方法也同样适用
还可以结合reversed()等方法灵活运用

相关文章

网友评论

      本文标题:Swift_遍历方法for in 和 array.forEach

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