显示外汇字典键/值对
Displaying Foreign Exchange Dictionary Key / Value Pairs
这是对 上提出的问题的跟进。我需要一些帮助来显示汇率条目。我知道这是一个字典键/值,但我不确定如何从结构中提取每个字符串/双对。
这是从 API 收到的典型字符串格式:
{
"rates": { "CAD": 1.5497, "HKD": 9.2404, "ISK":159.0 },
"base": "EUR",
"date": "2020-11-27"
}
struct RateResult: Codable {
let rates: [String: Double]
let base, date: String
}
struct ContentView: View {
@State private var results = RateResult(rates: [:], base: "", date: "")
var curr = "EUR"
var body: some View {
Text("Base Currency = \(results.base)")
Text("Date = \(results.date)")
List(results, id: \.results.rates) { item in
VStack(alignment: .leading) {
Text(results.rates[item.key])
Text(results.rates[item.value])
}
}
.onAppear(perform: loadData)
}
func loadData() {
}
}
要从字典中获取 key/value 对的数组,您可以使用 .map
:
let dict = ["one": 1, "two": 2, "three": 3]
let pairs = dict.map { ([=10=], ) } // ex: [("one": 1"), ("three": 3), ("two": 2)]
因此,您可以在 List
:
中使用相同的内容
List(results.rates.map { ([=11=], ) }, id: \.0) { currency, rate in
VStack {
Text(currency)
Text("\(rate)")
}
}
这是对
这是从 API 收到的典型字符串格式:
{
"rates": { "CAD": 1.5497, "HKD": 9.2404, "ISK":159.0 },
"base": "EUR",
"date": "2020-11-27"
}
struct RateResult: Codable {
let rates: [String: Double]
let base, date: String
}
struct ContentView: View {
@State private var results = RateResult(rates: [:], base: "", date: "")
var curr = "EUR"
var body: some View {
Text("Base Currency = \(results.base)")
Text("Date = \(results.date)")
List(results, id: \.results.rates) { item in
VStack(alignment: .leading) {
Text(results.rates[item.key])
Text(results.rates[item.value])
}
}
.onAppear(perform: loadData)
}
func loadData() {
}
}
要从字典中获取 key/value 对的数组,您可以使用 .map
:
let dict = ["one": 1, "two": 2, "three": 3]
let pairs = dict.map { ([=10=], ) } // ex: [("one": 1"), ("three": 3), ("two": 2)]
因此,您可以在 List
:
List(results.rates.map { ([=11=], ) }, id: \.0) { currency, rate in
VStack {
Text(currency)
Text("\(rate)")
}
}