How to follow several guard instructions in a loop?

How can I execute more than one guard statement in a loop without exiting the loop? If one security argument fails, it kicks me out of the current iteration of the loop 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 to ensure that all statements are executed for each user? Putting a return and break inside else blocks doesn't work either. Thank!

+4
source share
1 answer

The purpose of the guard statement is to check the condition (or try to expand the optional one), and if this condition is false or the parameter is nil, then you want to leave the current area in which you are.

, ( ) " ... ".

, 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 guard, , if let .

+4

All Articles