Swift 中的多态序列化——访问枚举的值

问题描述 投票:0回答:0

我正在使用 Github 的 graphQL API 来获取 macOS 应用程序的问题和拉取请求。由于这两种类型都包含在具有相似结构的对象中,因此我想使用多态序列化。

这是我的 Codable DTO:

struct Edge: Codable {
    var node: Node

    enum CodingKeys: String, CodingKey {
        case node
    }
}

enum Node: Codable {
    case pull(Pull)
    case issue(Issue)
    
    init (from decoder: Decoder) throws {
        if let pull = try? Pull(from: decoder) {
            self = .pull(pull)
        } else if let issue = try? Issue(from: decoder) {
            self = .issue(issue)
        }  else {
            try self.init(from: decoder) // this will fail!
        }
    }
    
    func encode(to encoder: Encoder) throws {
        switch self {
        case .issue(let issue):
            try issue.encode(to: encoder)
        case .pull(let pull):
            try pull.encode(to: encoder)
        }
    }
}

struct Pull: Codable {
    var title: String
    var isDraft: Bool
    
    enum CodingKeys: String, CodingKey {
        case isDraft
    }
}

struct Issue: Codable {
    var title: String
    var author: User
    
    enum CodingKeys: String, CodingKey {
        case title
        case author
    }
}

JSON 响应已序列化且没有错误,但我无法访问该对象。如何从节点获取 Pull 或 Issue 对象?

在调试模式下,我可以看到节点以某种方式被转换为拉取或问题:

但是到目前为止我尝试的一切都出错了:

edge.node.title   //Value of type 'Node' has no member 'title'
Pull(edge.node)   //Argument type 'Node' does not conform to expected type 'Decoder'
edge.node as Pull // Cannot convert value of type 'Node' to type 'Pull' in coercion
swift serialization enums polymorphism
© www.soinside.com 2019 - 2024. All rights reserved.