在swift中,for in和forEach都可以用来循环遍历.但for in 能使用 return、break、continue 关键字,forEach 不能使用 break、continue 关键字,但可以使用return.但使用return时他们的区别是:
在 for in 中,return 会导致循环终止,而在forEach中return不会导致循环终止,仅仅是跳出当前循环,继续进行下次循环,类似于continue的功能
let array = ["1", "2", "3", "4", "5"]
for element in array {
if element == "3" {
return
}
print(element)
}
// 输出:
// 1
// 2
let array = ["1", "2", "3", "4", "5"]
array.forEach { (element) in
if element == "3" {
return
}
print(element)
}
// 输出:
// 1
// 2
// 4
// 5
网友评论