How to properly set up a For- In Loop within a Guard statement?

583 Views Asked by At

I'm trying to set up a loop to retrieve info from inside a json dictionary but the dictionary is in a guard statement:

 guard let resultsDictionary = jsonDictionary["result"] as? [[String : Any]]?,
    let costDictionary = resultsDictionary?[0],
    let cost = costDictionary["cost"] as? [String: Any],

    let airbnb = cost["airbnb_median"] as? [String: Any]{
    for air in airbnb {
      let airbnbUS = air["USD"] as Int
      let airbnbLocal = air["CHF"] as Int
    }
    else {
      print("Error: Could not retrieve dictionary")
      return;
  }

When I do this I get multiple errors:

Expected 'else' after 'guard' condition, Variable declared in 'guard' condition is not usable in its body, Braced block of statements is an unused closure

I'm not sure why it doesnt work

2

There are 2 best solutions below

0
On BEST ANSWER

The syntax for guard is:

guard [expression] else {
  [code-block]
}

You want to use if instead:

if let resultsDictionary = jsonDictionary["result"] as? [[String : Any]]?,
 let costDictionary = resultsDictionary?[0],
 let cost = costDictionary["cost"] as? [String: Any],
 let airbnb = cost["airbnb_median"] as? [String: Any]{
    ...for loop here...
} else {
    ...error code here...
}

Or you can say:

guard let resultsDictionary = jsonDictionary["result"] as? [[String : Any]]?,
 let costDictionary = resultsDictionary?[0],
 let cost = costDictionary["cost"] as? [String: Any],
 let airbnb = cost["airbnb_median"] as? [String: Any] else {
    ...error code here...
    return  // <-- must return here
}

...for loop here, which will only run if guard passes...
1
On

Here you should use if let like:

    if let resultsDictionary = jsonDictionary["result"] as? [[String : Any]]?,
    let costDictionary = resultsDictionary?.first,
    let cost = costDictionary["cost"] as? [String: Any],
    let airbnb = cost["airbnb_median"] as? [String: Any] {
      for air in airbnb {
        let airbnbUS = air["USD"] as Int
        let airbnbLocal = air["CHF"] as Int
        ...any other statements...
      }
    } else {
      print("Error: Could not retrieve dictionary")
      return
    }

This can you help to decide when to use guard