繁体   English   中英

子类化 swift 通用可解码类型

[英]Subclassing swift generic decodable type

编辑:正如Rob Napier 所写,问题存在于 Xcode 9.2 中。 在 Xcode 9.3 中,该问题不再相关。

我的服务器 json 响应都打包在data对象中:

{ 
    "data": {...}
}

所以我有以下通用类型来解析 JSON:

class DataContainer<T: Decodable>: Decodable {

    let data: T

    init(data: T)
        self.data = data
    }
}

大多数情况下它工作正常,但有一个响应,我还需要解析included字段,因此我创建了SpecificDataContainer子类:

class SpecificDataContainer: DataContainer<DataObject> {
    let included: [IncludedObject]

    init() {
        included = []
        super.init(data: DataObject(id: ""))
    }
}

上面的实现给了我编译器错误'required' initializer 'init(from:)' must be provided by subclass of 'DataContainer'

我在SpecificDataContainer实现了init(from:)但编译器仍然给我同样的错误。

似乎我在这里错过了一些明显的东西。 我做错了什么? 这是我的完整代码:

import Foundation

let jsonData = """
{
    "data": {
        "id": "some_id"
    },
    "included": [
        {
            "id": "some_id2"
        }
    ]
}
""".data(using:.utf8)!

struct DataObject: Decodable {
    let id: String
}

struct IncludedObject: Decodable {
    let id: String
}

class DataContainer<T: Decodable>: Decodable {
    let data: T

    init(data: T) {
        self.data = data
    }
}

class SpecificDataContainer: DataContainer<DataObject> {
    let included: [IncludedObject]

    init() {
        included = []
        super.init(data: DataObject(id: ""))
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        var includedArray = try container.nestedUnkeyedContainer(forKey: .included)

        var includedObjects:[IncludedObject] = []
        while !includedArray.isAtEnd {
            let includedObject = try includedArray.decode(IncludedObject.self)
            includedObjects.append(includedObject)
        }
        self.included = includedObjects

        try super.init(from: decoder)
    }

    private enum CodingKeys: String, CodingKey {
        case data = "data"
        case included = "included"
    }
}

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
if let obj = try? decoder.decode(SpecificDataContainer.self, from: jsonData) {
    print("object id \(obj.data.id)")
} else {
    print("Fail!")
}

出于某种原因,Xcode 无法识别Codable子类中自动生成的init(from:) (正如 Rob 所说,这可能是一个错误)。 在 Xcode 9.3 发布之前,您还可以通过将初始化程序添加到基类来解决此问题:

class DataContainer<T: Decodable>: Decodable {    
    let data: T

    enum CodingKeys: String, CodingKey {
        case data
    }
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        data = try container.decode(T.self, forKey: .data)
    }

这似乎是 Xcode 9.2 中的一个错误。 在 9.3b4 中,您的代码很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM