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