2016-12-30 106 views
-1

我試圖建立一個循環,從一個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

回答

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

+2

不需要轉換爲可選數組''jsonDictionary [「result」] as? [[String:Any]]'並且resultsDictionary對數組的命名具有誤導性 –