1
我是Swift新手,我正在轉換一些Objective-C代碼。我有從數據庫中讀取ID和電影流派的代碼。我需要循環瀏覽這些信息,但我無法弄清楚如何統計id /流派信息。我有現在的硬編碼:Swift 3:計數從JSON讀取的數據
let url = URL(string: "https://api.themoviedb.org/3/genre/movie/list?api_key=818396bc0172f0f1d446cb4ffc92b7d8&language=en-US")
do {
let allData = try Data(contentsOf: url!)
let info = try JSONSerialization.jsonObject(with: allData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
if let results = info["genres"] {
print(results)
for x in 0...18 { // I don't want to hardcode the number 18
let id = results[x] as! [String : AnyObject]
print(id)
}
}
} catch {
}
我將在那裏我存儲在一個字典和快速列舉的信息,通過它的Objective-C的項目:
NSURL *url = [[NSURL alloc]initWithString:GENRES_LINK];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSDictionary *results = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil] objectForKey:@"genres"];
NSMutableString *genres = [NSMutableString stringWithString:@"Genres: "];
for (NSDictionary *key in [self.movies[x] objectForKey:@"genres"]) {
for (NSDictionary *key2 in results) {
if ([[key2 objectForKey:@"id"] isEqual:key]) {
[genres appendString:[NSString stringWithFormat:@"%@. ",[key2 objectForKey:@"name"]]];
break;
}
}
}
你試過'的(鍵,值)的結果{...}'?這應該讓你訪問該特定json對象中的所有鍵/值對。 –
您正在尋找Swift中相應的「for-in」/「for each」循環(這將是您尋找研究的關鍵詞):https://developer.apple.com/library/內容/文檔/雨燕/概念/ Swift_Programming_Language/ControlFlow.html – Larme