Swift泛型-无法从函数返回专用泛型

时间:2019-06-25 15:52:16

标签: swift generics promisekit

好,因此此示例使用PromiseKit,但它可能适用于其他任何内容

我具有以下功能

    static func apiCall<T>(type: T.Type,
                           url: String,
                           method: HTTPMethod,
                           params: Parameters?) -> Promise<T> where T: Codable

以及以下两个定义:

    protocol MyProtocol {} 
    struct MyStruct: MyProtocol, Codable {}

(那些显然不是空的,但是在这里没关系)

现在,当我尝试使用这种方法时:

    static func retrieveStuff() -> Promise<MyProtocol> {
        return BaseClient.apiCall(type: MyStruct.self,
                                  url: "bla",
                                  method: .get,
                                  params: nil)
    }

由于"Cannot convert return expression of type 'Promise<MyStruct>' to return type 'Promise<MyProtocol>'"

,因此无法编译

这确实起作用:

    static func retrieveStuff() -> Promise<MyProtocol> {
        return BaseClient.apiCall(type: MyStruct.self,
                                  url: "bla",
                                  method: .get,
                                  params: nil).map { d -> MyProtocol in
                                    // I have no idea, why i have to do this

                                    return d
        }
    }

为什么此转换步骤实际上没有做任何必要的事情。由于协议继承,Promise是否应该不是有效的Promise?

很抱歉,这是一个常见问题,但目前我不知道要实际搜索什么

0 个答案:

没有答案