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

时间:2016-12-30 21:55:32

标签: ios json swift guard

我正在尝试设置一个循环来从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;
  }

当我这样做时,我会遇到多个错误:

  

在'后卫'状态后预期'其他',    在“保护”条件下声明的变量在其体内不可用,    支撑语句块是未使用的闭包

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

在这里你应该使用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