Search code examples
iosjsonswiftguard

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


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


Solution

  • 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...