如何使用SwiftyJSON循环JSON?

我有一个我可以用SwiftyJSONparsing的json:

if let title = json["items"][2]["title"].string { println("title : \(title)") } 

完美的作品。

但我无法循环。 我试了两种方法,第一种是

 // TUTO : //If json is .Dictionary for (key: String, subJson: JSON) in json { ... } // WHAT I DID : for (key: "title", subJson: json["items"]) in json { ... } 

XCode不接受for循环声明。

第二种方法:

 // TUTO : if let appArray = json["feed"]["entry"].arrayValue { ... } // WHAT I DID : if let tab = json["items"].arrayValue { ... } 

XCode不接受if语句。

我究竟做错了什么 ?

如果你想循环通过json["items"]数组,请尝试:

 for (key, subJson) in json["items"] { if let title = subJson["title"].string { println(title) } } 

至于第二个方法, .arrayValue返回 Optional数组,你应该使用.array代替:

 if let items = json["items"].array { for item in items { if let title = item["title"].string { println(title) } } } 

我觉得有点奇怪的解释我自己,因为实际上使用:

 for (key: String, subJson: JSON) in json { //Do something you want } 

给出了语法错误(在Swift 2.0 atleast中)

正确的是:

 for (key, subJson) in json { //Do something you want } 

确实key是一个string,subJson是一个JSON对象。

不过,我喜欢做一点点不同,这里是一个例子:

 //jsonResult from API request,JSON result from Alamofire if let jsonArray = jsonResult?.array { //it is an array, each array contains a dictionary for item in jsonArray { if let jsonDict = item.dictionary //jsonDict : [String : JSON]? { //loop through all objects in this jsonDictionary let postId = jsonDict!["postId"]!.intValue let text = jsonDict!["text"]!.stringValue //...etc. ...create post object..etc. if(post != nil) { posts.append(post!) } } } } 

在for循环中, key的types不能是"title"types。 由于"title"是一个string,所以: key:String 。 然后在循环内,你可以专门使用"title"当你需要它。 而且subJson的types也必须是JSON

而且由于JSON文件可以被视为一个二维数组,所以json["items'].arrayValue将返回多个对象,强烈build议使用: if let title = json["items"][2].arrayValue

看看: https : //developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html

请检查自述文件

 //If json is .Dictionary for (key: String, subJson: JSON) in json { //Do something you want } //If json is .Array //The `index` is 0..<json.count's string value for (index: String, subJson: JSON) in json { //Do something you want }