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

时间:2016-05-07 03:14:23

标签: ios swift nsdictionary 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)
}

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

1 个答案:

答案 0 :(得分:5)

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语句中的guard let将允许您在guard语句之后访问展开的值,因为if let只允许您访问以下区块内的值。

相关问题