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

问题描述:

我试图建立一个循环,从一个JSON字典中检索信息,但字典是在保护声明:如何在Guard语句中正确设置For-In循环?

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

你'guard'逻辑是遥远 - 语法'后卫陈述其他{/ *错误处理* /}/*使用的Airbnb * /' – luk2302

+0

常规逻辑虽然这个问题应该有可能因为基于意见而关闭,如果有一种标准化的方式来表达这一点,那将是非常好的。对我来说,@i_am_jorf应该是第二种方式。 – jjatie

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

+2

不需要转换为可选数组''jsonDictionary [“result”] as? [[String:Any]]'并且resultsDictionary对数组的命名具有误导性 –