-1

我想知道当在 Swift 中从 JSON 加载数据时,是否可以在 struct 中自动将数据从数组变量加载到字典变量?

假设我有如下数据

 "values": [
      {
        "name": "string",
        "value": 10
      },
      {
        "name": "string1",
        "value": 20
      },
      {
        "name": "string2",
        "value": 30
      },
      {
        "name": "string3",
        "value": 40
      }
    ]

我有这样的结构

struct Val: {

    let name: String
    let value: Double

}

struct Measure {

    let id = UUID()
    let values: [Val]
    var dictionaryValues: [String: Double] // <- this variable I would like to set automatically from data from array Val  [name: value]

}

这可能吗?我尝试使用 {set get} 或者我应该在 Val 数组上使用 didSet 观察者并提供字典值?

谢谢

4

1 回答 1

0

您可以声明dictionaryValues为计算属性

struct Measure {

    let id = UUID()
    let values: [Val]
    var dictionaryValues: [String: Double] {
        var result = [String: Double]()
        values.forEach { result[$0.name] = $0.value }
        return result
    }
}
于 2020-01-01T21:06:54.320 回答