如何在 Guard 语句中正确设置 For-In 循环?

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

我正在尝试设置一个循环以从 json 字典中检索信息,但该字典位于保护语句中:

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

执行此操作时出现多个错误:

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

我不确定为什么它不起作用

guard 的语法是:

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

您想改用 if

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

或者你可以说:

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

在这里你应该使用 if let 比如:

    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