[英]What is the right way to decode categories array in Swift
For example, I have例如,我有
[{
"name": "Afghanistan",
"numericCode": "004",
"altSpellings": ["AF", "Afġānistān"],
"currencies": [{
"code": "AFN",
"name": "Afghan afghani",
"symbol": "؋"
}]
},
...
To get the "altSpellings" and "currencies", how would I build my Model?要获得“altSpellings”和“currencies”,我将如何构建我的 Model?
struct WorldData: Identifiable, Decodable {
var id: String {
return numericCode
}
var name: String
var numericCode : String
var altSpellings : Array
var currencies : ???
}
and, if my API object doesn't have an ID, would it be like:并且,如果我的 API object 没有 ID,会是这样:
var id: ObjectIdentifier
Thank you!谢谢!
Create another struct Currency
for currencies
and for altSpellings
it's just [String]
.为
currencies
和altSpellings
创建另一个结构Currency
,它只是[String]
。
struct WorldData: Identifiable, Decodable {
let name, numericCode: String
let altSpellings: [String]
let currencies: [Currency]
var id: String {
return numericCode
}
}
struct Currency: Decodable {
let code, name, symbol: String
}
Then decode using [WorldData]
.然后使用
[WorldData]
解码。
do {
let decodedWorldData = try JSONDecoder().decode([WorldData].self, from: data)
print(decodedWorldData)
} catch {
print(error)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.