这是我的回应,这个数组我需要解码。
[
{id: 1, name: "John"},
{id: 2, name: "Amanda"}
]
答案 0 :(得分:1)
当您说解码时,我假设您是从某个端点获取此数据的。我要做的是创建一个类似Codable的结构:
struct ClassName : Codable {
let id : Int
let name : String
}
而不是解码数据:
if let array = try? JSONDecoder().decode([ClassName].self, from: jsonData) {
// array will contain your data
}
如果有时缺少端点中的某些数据,请确保在模型中将其标记为可选。
答案 1 :(得分:0)
您的响应只是一个数组。所以要相应地对待它。
var ids = [Int]()
var names = [String]()
let response = [{id: 1, name: "John"}, {id: 2, name: "Amanda"}]
for i in 0...response.count - 1 {
ids = response[i]["id"]
names = response[i]["name"]
}
或者如果您想将其转换为字典:
var dictionary = [Int: String]()
let response = [{id: 1, name: "John"}, {id: 2, name: "Amanda"}]
for i in 0...response.count - 1 {
dictionary[response[i]["id"]] = response[i]["name"]
}