我是REST API的新手,遇到了一些麻烦。我正在尝试从嵌套在字典中的数组调用数据。虽然我已经能够从其他变量中提取数据,但这给了我一些问题。作为参考,我需要的URL在“sprites”数组中标记为“front default”。此外,URL是图像的URL,我使用Alamofire图像来显示图像。我将包含我迄今使用的代码来调用其他变量,以及API结构的屏幕截图。
import Foundation
import Alamofire
import AlamofireImage
import SwiftyJSON
import Siesta
class PokeInfo {
var name: String
var id: Int
var abilities: [String]
var types: [String]
// converts dictionary into string
init?(jsonDictionary: [String: Any]) {
//guard used to check if value entered in search bar matches a name in API data
guard let name = jsonDictionary["name"] as? String,
let id = jsonDictionary["id"] as? Int,
//abilities data nested. First must be set to string
let abilities = jsonDictionary["abilities"] as? [[String: Any]],
let types = jsonDictionary["types"] as? [[String: Any]]
else {
return nil
};
var abilityNames: [String] = []
var typeNames: [String] = []
//targets nested data, going inside dictionary to find attributes of that element
for abilityDictionary in abilities {
guard let ability = abilityDictionary["ability"] as? [String: Any], let name = ability["name"] as? String else { break }
abilityNames.append(name)
};
for typeDictionary in types {
guard let type = typeDictionary["type"] as? [String: Any], let name = type["name"] as? String else { break }
typeNames.append(name)
}
self.name = name
self.id = id
self.abilities = abilityNames
self.types = typeNames
}
}
答案 0 :(得分:0)
从Swift 4开始,你应该使用Codable作为JSON,现在是语言的一部分。这是一个游乐场的例子:
db.collection.findOne().sort({$natural:-1}).limit(1);
输出是:
import PlaygroundSupport
import UIKit
class PokeInfo: Codable {
var name: String
var id: Int
var abilities: [String]
var types: [String]
}
let pokeString = """
{
"name": "test",
"id": 1,
"abilities": ["a", "b", "c"],
"types": ["x", "y", "z"]
}
"""
let pokeData = pokeString.data(using: .utf8)!
let decoder = JSONDecoder()
let pokeInfo = try! decoder.decode(PokeInfo.self, from: pokeData)
print(pokeInfo.abilities)