簡體   English   中英

如何在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;
  }

當我這樣做時,我會遇到多個錯誤:

在“警衛”條件之后預期為“其他”,在“警衛”條件中聲明的變量在其主體中不可用,語句的括號塊是未使用的閉包

我不確定為什么它不起作用

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
    }

這可以幫助您決定何時使用guard

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM