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!
The purpose of the guard statement is to check a condition (or attempt to unwrap an optional) and if that condition is false or the option is nil then you want to exit from the current scope you are in.
Imagine that the guard statement is saying (in Gandalf's voice) "You shall not pass... if you do not meet this condition".
What you want to do here can be simply done with if let
statements:
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
}
One thing to note is that the guard let
in the guard statement will allow you to access the unwrapped value after the guard
statement where as the if let
will only allow you to access that value within the following block.