-1

I wonder if is possible to load data from array variable to dictionary variable automatically in struct when data is loaded from JSON in Swift?

Let say I have data which looks like below

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

I have struct like this

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]

}

Is this possible? I tried with {set get} or maybe should I use didSet observer on Val array and feed dictionaryValues?

Thanks

Pa Bloo
  • 51
  • 1
  • 3

1 Answers1

0

You could declare dictionaryValues as computed property

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
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361