Swift -如何更改JSON结构元素值



我已经将JSON数据文件转换为使用JSONDocode的deviceParametersStruct实例,它工作正常。然而,我正在努力改变结构上的属性值编程之后。任何建议吗?

struct DeviceParameters : Codable, Hashable {

let id : String
let version : String
let encoding : String
let deviceType : String // name of XML file is converted to deviceName, unique identifier
var Point : [PointData]

enum CodingKeys: String, CodingKey {
case id, version, encoding, Point
case deviceType = "name"
}
}
struct PointData : Codable, Hashable {
let id : String
var name : String
let type : String
var address : Address
let calculate : Calculate
let pointEnum: [String: String]
var presentValue : String

enum CodingKeys: String, CodingKey {
case id, name
case type = "Type"
case address = "Address"
case calculate = "Calculate"
case pointEnum = "Enum"
case presentValue
}

}
struct Calculate: Codable, Hashable {
let scaling, decimals, min, max: String?
}
struct Address: Codable, Hashable {
var index: String
let type: String
let format: String
}

使用ForEach我可以滚动打印结构参数,但我不能给变量赋新值。正确的方法是什么?也许最简单的是什么?

func updatePresentValue(pointNo : Int) {

deviceParameters.Point.forEach {
print($0.name) // prints the name of the "Point" OK
print($0.address.index) // prints the name of the "Point.Address" OK
$0.presentValue = "200" // Not working telling $0 inmutable
$0.address.index = "20"  // Not working telling $0 inmutable
}
}

首先确保变量名以小写字母开头,这是公认的编码实践。

闭包参数是不可变的,不能赋新值。但是你可以使用map操作符,复制你的结构体,赋新值,并在闭包中返回该副本。

func updatePresentValue(pointNo : Int) {
deviceParameters.points = deviceParameters.points.map { point in
var p = point
p.address.index = "New value"
return p
}
}

最新更新