如何在循环中执行多个 guard 语句?

How do I execute multiple guard statements within a loop?

如何在不跳出循环的情况下在一个循环中执行多个 guard 语句?如果一个 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)
}

如何确保为每个用户执行所有语句?将 return 和 break 放在 else 块中也不起作用。谢谢!

guard 语句的目的是检查一个条件(或尝试解包一个可选的),如果该条件为假或选项为 nil 那么你想退出你所在的当前范围。

假设警卫声明说(用甘道夫的声音)"You shall not pass... if you do not meet this condition"。

你想在这里做的事情可以简单地用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 语句中的 guard let 将允许您访问 guard 语句之后的解包值,而 if let 只允许您访问在以下块中访问该值。