【问题标题】:How to properly set up a For- In Loop within a Guard statement?如何在 Guard 语句中正确设置 For-In 循环?
【发布时间】:2017-01-01 00:28:15
【问题描述】:

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

当我这样做时,会出现多个错误:

在 'guard' 条件之后预期的 'else', 在“守卫”条件下声明的变量在其主体中不可用, 大括号语句块是未使用的闭包

我不知道为什么它不起作用

【问题讨论】:

  • 你的 guard 逻辑很不靠谱 - 语法是 guard statements else { /* error handling */ } /* the regular logic using airbnb */
  • 虽然这个问题可能会因为基于意见而被关闭,但如果有一种标准化的方式来表达这一点,那就太好了。对我来说,@i_am_jorf 应该是第二种方式。

标签: ios json swift guard


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 不需要强制转换为可选数组jsonDictionary["result"] as? [[String : Any]] 并且 resultsDictionary 会误导数组命名
    猜你喜欢
    • 1970-01-01
    • 2019-05-28
    • 2021-01-01
    • 2021-02-20
    • 1970-01-01
    • 2014-06-08
    • 2015-04-26
    • 2015-04-21
    • 1970-01-01
    相关资源
    最近更新 更多