user3353890 user3353890 - 6 months ago 14
Swift Question

How do I execute multiple guard statements within a loop?

How can I execute more than one guard statement in a loop without breaking out of the loop? If one guard statement fails, it kicks me out of the current loop iteration and bypasses the remaining code.

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)
}


How do I ensure that all of the statements are executed for each user? Putting return and break within the else blocks does not work either. Thanks!

Answer

The whole purpose of the guard statement is that if the the condition is false the current scope is exited. Imagine that the guard statement is saying (in Gandalf's voice) "you shall not pass if you do not meet this requirement". What you want to do here involves using if let statements.

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