2016-01-28 94 views
2

我看了一下其他問題,但似乎找不到能解答我的問題的問題。使用SwiftyJSON和Alamofire循環瀏覽JSON

我有這個JSON文件:

[ 
"posts", 
{ 
    "2015": [ 
    "post title one" 
    ], 
    "2016": [ 
    "post title one", 
    "post title two" 
    ] 
} 
] 

,我有這樣的代碼在我的雨燕文件:

Alamofire.request(.GET, url).validate().responseJSON { response in 
     switch response.result { 
     case .Success: 
      if let value = response.result.value { 
       let json = JSON(value) 
       for (key, subJson) in json["posts"] { 
        if let year = subJson.string { 
         print(year) 
        } 
       } 
      } 
     case .Failure(let error): 
      print(error) 
     } 
    } 

我可以從服務器獲取ok了JSON。

在此行中:

for (key, subJson) in json["posts"] { 

我得到這個錯誤:

immutable value 'key' was never used, consider replaying with '_' or removing it

我試過了,並試圖消除它 - 仍然沒有顯示在控制檯中。

而且,在這條線:

if let year = subJson.string { 

我得到這個錯誤:

Value of tuple type 'Element' (aka '(String, JSON)') has no member 'string'

我想要做的是這樣的:

遍歷所有這些年來,把他們在一個可用視圖。有人可以幫忙嗎?

回答

2

做這樣的:

for (_, subJson) in json["posts"] { 
    for (year, content) in subJson { 
     print(year) 
    } 
} 

第一個錯誤是隻是一個警告,這意味着你永遠不會使用「鑰匙」變量,所以編譯器建議不要進行標記。在我的示例中,由於我們沒有使用它,您將收到content的類似警告:要麼使用它,要麼用_替換它。

請注意,我從您的代碼推斷出您的JSON格式,因爲您的JSON代碼段看起來好像不是有效的/不是實際的。

UPDATE:

for (_, subJson) in json["posts"] { 
    for (year, content) in subJson { 
     print(year) 
     for (_, title) in content { 
      print(title) 
     } 
    } 
} 
+0

應如何JSON看?我用PHP來生成它,所以也許我做錯了.. – JamesG

+0

Gunna現在嘗試你的解決方案。 – JamesG

+0

我得到了不可改變的值'內容'從來沒有使用過,請考慮用'_'重放或刪除它 – JamesG