Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Swift中从JSON加载数据时,在struct中将数据从数组变量自动加载到字典变量_Swift_Accessor_Property Observer - Fatal编程技术网

在Swift中从JSON加载数据时,在struct中将数据从数组变量自动加载到字典变量

在Swift中从JSON加载数据时,在struct中将数据从数组变量自动加载到字典变量,swift,accessor,property-observer,Swift,Accessor,Property Observer,我想知道在Swift中从JSON加载数据时,是否可以在struct中将数据从数组变量自动加载到字典变量 假设我有如下数据 "values": [ { "name": "string", "value": 10 }, { "name": "string1", "value": 20 }, { "name": "string2", "value

我想知道在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]

}
struct Val:{
let name:String
让值加倍
}
结构度量{
设id=UUID()
let值:[Val]

var dictionaryValues:[字符串:Double]/您可以将
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
    }
}