可编码表中单个数据的多个编码键



我使用的API支持多语言。例如:

// For Japanese
{
"earthquake_detail": {
"advisory_title_ja": "津波注意報",
"depth_title_ja": "震源深さ",
"depth_value_ja": "30km",
}
}
// For English
{
"earthquake_detail": {
"advisory_title_en": "Tsunami Advisory",
"depth_title_en": "Depth",
"depth_value_en": "30km",       
}
}

我正在使用swift-codable将它们映射到一个结构。有没有一种方法可以将多个编码键映射到一个变量?这是我的swift结构。

struct EarthquakeDetail: Codable {
var advisoryTitle, depthTitle, depthValue: String?
enum CodingKeys: String, CodingKey {
case advisoryTitle = "advisory_title_ja"
case depthTitle = "depth_title_ja"
case depthValue = "depth_value_ja"
}
}

我想获得的是日语这将是编码密钥:

enum CodingKeys: String, CodingKey {
case advisoryTitle = "advisory_title_ja"
case depthTitle = "depth_title_ja"
case depthValue = "depth_value_ja"
}

英语:

enum CodingKeys: String, CodingKey {
case advisoryTitle = "advisory_title_en"
case depthTitle = "depth_title_en"
case depthValue = "depth_value_en"
}

如果不打算使用convertFromSnakeCase策略,请添加一个自定义密钥解码策略,从三个编码密钥中删除_xx

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom { codingKeys in
let lastKey = codingKeys.last!
if lastKey.intValue != nil || codingKeys.count != 2 { return lastKey }
if codingKeys.dropLast().last!.stringValue != "earthquake_detail" { return lastKey }
return AnyCodingKey(stringValue: String(lastKey.stringValue.dropLast(3)))!
}

如果earthquake_detail键比第2级更深,则相应地更改!= 2

为了能够创建自定义编码密钥,您需要

struct AnyCodingKey: CodingKey {
var stringValue: String
var intValue: Int?
init?(stringValue: String) { self.stringValue = stringValue }
init?(intValue: Int) {
self.stringValue = String(intValue)
self.intValue = intValue
}
}

现在声明EarthquakeDetail如下

struct EarthquakeDetail: Codable {
var advisoryTitle, depthTitle, depthValue: String
enum CodingKeys: String, CodingKey {
case advisoryTitle = "advisory_title"
case depthTitle = "depth_title"
case depthValue = "depth_value"
}
}

相关内容

  • 没有找到相关文章

最新更新