微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何解码已经具有不同 API 解码逻辑的对象?

如何解决如何解码已经具有不同 API 解码逻辑的对象?

所以我像这样解码了一个 JSON,

class MatchDetailResponse: Codable {

static let DocumentsDirectory = FileManager().urls(for: .documentDirectory,in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("MatchDetailResponse")

var homeTeam: Team?
var awayTeam: Team?

enum CodingKeys: String,CodingKey {
    case homeTeam
    case awayTeam
}

func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(homeTeam,forKey: .homeTeam)
    try container.encode(awayTeam,forKey: .awayTeam)
}

private enum TopLevelKeys: String,CodingKey {
    case teams = "Teams"
    case matchDetail = "Matchdetail"
}

private enum MatchDetailKeys: String,CodingKey {
    case homeTeam = "Team_Home"
    case awayTeam = "Team_Away"
}

private struct DynamicCodingKeys: CodingKey {
    var stringValue: String
    init?(stringValue: String) {
        self.stringValue = stringValue
    }

    var intValue: Int?
    init?(intValue: Int) {
        return nil
    }
}

required init(from decoder: Decoder) throws {
    
    let container = try decoder.container(keyedBy: TopLevelKeys.self)
    let matchDetailContainer = try container.nestedContainer(keyedBy: MatchDetailKeys.self,forKey: .matchDetail)
    let homeTeamId = try matchDetailContainer.decode(String.self,forKey: MatchDetailKeys.homeTeam)
    let awayTeamId = try matchDetailContainer.decode(String.self,forKey: MatchDetailKeys.awayTeam)

    let teamContainer = try container.nestedContainer(keyedBy: DynamicCodingKeys.self,forKey: .teams)
    //Assign the home team & away team
    for key in teamContainer.allKeys {
        if key.stringValue == homeTeamId {
            homeTeam = try teamContainer.decode(Team.self,forKey: DynamicCodingKeys(stringValue: key.stringValue)!)
        }
        else if key.stringValue == awayTeamId {
            awayTeam = try teamContainer.decode(Team.self,forKey: DynamicCodingKeys(stringValue: key.stringValue)!)
        }
    }
}
}

如您所见,我收到了来自 API 的响应,我正在对其进行解码,一切正常。现在我的要求是存储它。所以我把它编码成这样。现在的问题是它何时会尝试解码存储的版本,因为解码函数是为 API 响应构建的,因此无法对其进行解码。

我的要求是,如何解码存储的 Codable 结构,以及我们究竟是如何做到的?任何帮助将不胜感激。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。