ios - 如何在可编码结构中使用计算属性(swift)

标签 ios json swift codable computed-properties

我创建了一个“可编码”结构来序列化数据集并将其编码为 Json。除了计算属性未显示在 json 字符串中外,一切都运行良好。如何在编码阶段包含计算属性。

例如:

struct SolidObject:Codable{

    var height:Double                      = 0
    var width:Double                       = 0
    var length:Double                      = 0

    var volume:Double {
        get{
            return height * width * length
        }
    }
}

var solidObject = SolidObject()
solidObject.height = 10.2
solidObject.width = 7.3
solidObject.length = 5.0

let jsonEncoder = JSONEncoder()
do {
    let jsonData = try jsonEncoder.encode(solidObject)
    let jsonString = String(data: jsonData, encoding: .utf8)!
    print(jsonString)
} catch {
    print(error)
}

打印出“{"width":7.2999999999999998,"length":5,"height":10.199999999999999}"

我也对 7.29999.. 而不是 7.3 感到好奇,但我的主要问题是“我怎样才能将“volume”也包含到这个 json 字符串中?

最佳答案

您需要手动编码/解码,而不是让自动化的东西为您完成。这在 Swift playground 中按预期工作。

struct SolidObject: Codable {

    var height:Double                      = 0
    var width:Double                       = 0
    var length:Double                      = 0

    var volume:Double {
        get{
            return height * width * length
        }
    }

    enum CodingKeys: String, CodingKey {
        case height
        case width
        case length

        case volume
    }

    init() { }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        height = try values.decode(Double.self, forKey: .height)
        width = try values.decode(Double.self, forKey: .width)
        length = try values.decode(Double.self, forKey: .length)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(height, forKey: .height)
        try container.encode(width, forKey: .width)
        try container.encode(length, forKey: .length)

        try container.encode(volume, forKey: .volume)
    }

}

var solidObject = SolidObject()
solidObject.height = 10.2
solidObject.width = 7.3
solidObject.length = 5.0

let jsonEncoder = JSONEncoder()
do {
    let jsonData = try jsonEncoder.encode(solidObject)
    let jsonString = String(data: jsonData, encoding: .utf8)!
    print(jsonString)
} catch {
    print(error)
}

关于ios - 如何在可编码结构中使用计算属性(swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49309815/

相关文章:

javascript - jqGrid - 将数据库记录嵌套属性设置为行 ID

c# - JSON 将自定义 C# 结构序列化为字符串,而不是对象

swift - 通过 AVMetaDataItem 写入 ID3 标签

ios - 删除UITableViewCell的最后一个分隔符

ios - base64EncodedStringWithOptions 在 SenTest 上崩溃

json - MVC3 DropDownList + JSON + 选定问题

ios - 在 Rx Swift 中自动将 UITableView 滚动到底部

ios - "textViewDidChange"Swift 的重新声明无效

ios - 我是否需要保留在闭包中引用的自动释放对象?

ios - 快速获取可用 wifi 网络列表并连接到其中之一