开启Swift类型,以检查其是否是通用的

时间:2019-11-14 12:01:57

标签: swift generics swift5.1

某些上下文:JSONAPI是编写JSON信封的标准方式,其中包括诸如分页,链接到相关对象以及到上一页,下一页等的内容。我的某些电话使用它,有些则没有。确实使用它的人应该对结果使用特殊的解析器,而常规结果只使用常规JSONDecoder。

我要编写以下代码:

    func parse<ResultType>(data: Data,
                           including includeList: String,
                           with httpResponse: HTTPURLResponse) throws -> ResultType where ResultType: Decodable {
        switch ResultType.self {
        case is some JSONAPIResult.Type: // Putting `some` here is not supported in Swift!
            return try jsonAPIDecoder.decode(ResultType.self, from: data, includeList: includeList)
        default:
            return try jsonDecoder.decode(ResultType.self, from: data)
        }
    }

这不会建立,因为我们不能像在返回类型中那样使用some。取而代之的是,我必须指定T JSONAPIResult需要符合使事情变得过于复杂的条件。

JSONAPIResult如下图:

    // using:
    struct JSONAPIResult<T: Decodable>: Decodable, JSONAPIMetaContaining {
        let data: T
        let meta: JSONAPIMeta
    }

我最终要做的是:

        // Ducktyping it through a protocol, not ideal but JSONAPIResult wants to know about T
        switch ResultType.self {
        case is JSONAPIMetaContaining.Type:
            return try jsonAPIDecoder.decode(ResultType.self, from: data, includeList: includeList)
        default:
            return try jsonDecoder.decode(ResultType.self, from: data)
        }
    }

此代码比我希望的要脆弱,因为它取决于该协议,而不取决于我应该发送给jsonAPIDecoderJSONAPIResult<T: Decodable>)的实际类型。有没有一种方法可以检查ResultTypeJSONAPIResult而不拖拽它的嵌套泛型T,因为我在这里不关心T

0 个答案:

没有答案