Swift中遍歷方法for in 和 forEach的區(qū)別

前言

在swift中,我們經常會用到的兩種快速遍歷的方法,一種是最常見也是最常用的for ... in ..., 另外一種也是不同于Objective-C的forEach。那么,兩者的使用有什么區(qū)別呢?今天,讓我們來聊一聊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中是當符合當前執(zhí)行語句時,程序直接終止到此并返回, 比如上面的元素 "4"、"5""Hello World" 沒有被執(zhí)行;而forEach中是當符合當前執(zhí)行語句時,程序跳過本次判斷繼續(xù)執(zhí)行, 比如上面的元素"4"、"5"、"Hello World"被執(zhí)行。

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\"")

錯誤: 程序根本不能執(zhí)行
error:continue is only allowed inside a loop

在使用continue關鍵字的時候,for in可以正常遍歷并且執(zhí)行,而且 continue的作用是跳出本次循環(huán),不影響后面的執(zhí)行; 而在 forEach中,swift是不允許這樣執(zhí)行的,報錯的原因是說 continue只允許出現在循環(huán)語句中,也就是說不能使用在 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\"")

錯誤:程序根本不能執(zhí)行
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來說是可以的,跳出本層循環(huán),也就是for循環(huán),然后繼續(xù)執(zhí)行后面的程序; 對于forEach來說,同continue關鍵字的效果一樣,swift不允許這樣使用,原因說的是break只能用于循環(huán)語句或switch語句,break會退出本層循環(huán)語句。

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關鍵字 的使用上有著本質的區(qū)別
  • 一般情況下,兩者都可通用,都方便、敏捷
  • for in 使用范圍比 forEach更廣

</br>

歡迎加入 iOS(swift)開發(fā)互助群:QQ群號:558179558, 相互討論和學習!你想要的答案這里都有...

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Swift提供了多種控制流聲明。包括while循環(huán)來多次執(zhí)行一個任務;if,guard和switch聲明來根據確定...
    BoomLee閱讀 2,072評論 0 3
  • 本章將會介紹 控制流For-In 循環(huán)While 循環(huán)If 條件語句Switch 語句控制轉移語句 continu...
    寒橋閱讀 816評論 0 0
  • Swift 提供了類似 C 語言的流程控制結構,包括可以多次執(zhí)行任務的for和while循環(huán),基于特定條件選擇執(zhí)行...
    窮人家的孩紙閱讀 780評論 1 1
  • 控制流 for循環(huán) for-in for while循環(huán) while repeat-while 條件語句 if s...
    zhenyu54閱讀 949評論 0 0
  • 我猜, 所謂的美好教主——鹿晗,絕不僅僅是一個教主那么簡單。 而是一個還不算太鮮明的劃分時代的界線。 很多年以來,...
    段童閱讀 264評論 0 1

友情鏈接更多精彩內容