簡體   English   中英

如何在循環中執行多個保護語句?

[英]How do I execute multiple guard statements within a loop?

如何在不中斷循環的情況下在循環中執行多個guard語句? 如果一個保護語句失敗,它會將我踢出當前循環迭代並繞過剩余的代碼。

for user in users {
    guard let first = user["firstName"] as? String else {
        print("first name has not been set")
        continue
    }
    print(first)

    guard let last = user["lastName"] as? String else {
        print("last name has not been set")
        continue
    }
    print(last)

    guard let numbers = user["phoneNumbers"] as? NSArray else {
        print("no phone numbers were found")
        continue
    }
    print(numbers)
}

如何確保為每個用戶執行所有語句? 在else塊中放置return和break也不起作用。 謝謝!

guard語句的目的是檢查條件(或嘗試解包一個可選項),如果該條件為false或選項為nil,則您要退出當前作用域。

想象一下,警衛聲明(用甘道夫的聲音說)“如果你不符合這個條件你就不會過去......”

你想在這里做什么可以簡單地用if let語句完成:

for user in users {
  if let first = user["firstName"] as? String {
    print(first)
  } else {
    print("first name has not been set")
  }
  //Do the same for the other fields
}

有一點要注意的是, guard let在中后衛聲明將允許你在訪問之后展開的價值guard聲明,其中作為if let只會讓你到以下塊中訪問該值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM