簡體   English   中英

Swift - 如何更改 JSON 結構元素值

[英]Swift - How to change JSON Struct Element Values

我已經使用 JSONDocode 將 JSON 數據文件轉換為 Struct 的deviceParameters實例,並且工作正常。 但是,之后我很難以編程方式更改 Struct 上的屬性值。 任何建議?

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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM