问题描述
我创建了一个可编码结构来序列化数据集并将其编码为Json。一切工作正常,除了json字符串中未显示计算出的属性。
I've created a "codable" struct to serialize a data set and encode it to Json. Everything is working great except the computed properties don't show in the json string. How can I include computed properties during the encode phase.
Ex:
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)
}
打印出 {宽度:7.2999999999999998,长度:5,高度:10.199999999999999}
prints out "{"width":7.2999999999999998,"length":5,"height":10.199999999999999}"
我也很好奇具有7.29999 ..而不是7.3,但我的主要问题是我如何也可以在此json字符串中包括 volume?
I am also curious about having 7.29999.. instead of 7.3 but my main question is "how can I include "volume" to this json string too"?
推荐答案
您需要手动编码/解码,而不是让自动化的东西替您完成。这在Swift操场上可以正常工作。
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)
}
这篇关于如何在可编码结构中使用计算属性(Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!