首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可编码的单个数据的多个编码密钥

可编码的单个数据的多个编码密钥
EN

Stack Overflow用户
提问于 2020-03-26 12:25:12
回答 1查看 94关注 0票数 1

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

代码语言:javascript
复制
// 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结构。

代码语言:javascript
复制
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"
    }
}

我想要获取的是日语,这将是编码密钥:

代码语言:javascript
复制
enum CodingKeys: String, CodingKey {
            case advisoryTitle = "advisory_title_ja"
            case depthTitle = "depth_title_ja"
            case depthValue = "depth_value_ja"
        }

对于英语:

代码语言:javascript
复制
enum CodingKeys: String, CodingKey {
            case advisoryTitle = "advisory_title_en"
            case depthTitle = "depth_title_en"
            case depthValue = "depth_value_en"
        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-26 13:55:42

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

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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,如下所示

代码语言:javascript
复制
struct EarthquakeDetail: Codable {
    var advisoryTitle, depthTitle, depthValue: String

    enum CodingKeys: String, CodingKey {
        case advisoryTitle = "advisory_title"
        case depthTitle = "depth_title"
        case depthValue = "depth_value"
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60861011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档