How to use computed property in a codable struct (swift)

安稳与你 提交于 2019-12-03 12:19:12

You need to manually encode/decode instead of letting the automated stuff do it for you. This works as expected in a 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)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!