我有一个通用Struct数组,该结构的通用类型扩展了类ResponseBase
。在我尝试附加到responseMapping
数组的函数中,但没有运气,它总是出现以下错误:Error: Cannot convert value of type 'ResponseMap<ResponseType>' to expected argument type 'ResponseMap<ResponseBase>'
。我已经尝试添加Any,AnyClass,AnyObject或任何Any作为Type,但是它也没有真正实现。
我尝试使用Type Erasure来做到这一点,但我感到困惑,于是我放弃了。有人知道如何正确执行此操作吗?
代码
struct ResponseMap<ResponseType: ResponseBase> {
var fulfill: (ResponseType) -> ()
}
public class MessengerTest {
var responseMapping = [ResponseMap]()
func send<ResponseType, Type>(_ message: Type) -> Promise<ResponseType> where ResponseType: ResponseBase, Type: Base<ResponseType> {
return Promise<ResponseType> { resolver in
let map = ResponseMap(fulfill: resolver.fulfill)
self.responseMapping.append(map) <---- Error
}
}
}
更新 这是引发相同错误但没有PromiseKit的代码。
class Promise<U> {
let fulfill: (U)->Void
init() {
fulfill = {U in
print("fulfill")
}
}
}
class Base {
}
class Response: Base {
}
class Response1: Base {
}
struct ResponseMap<U: Base> {
let fulfill: (U)->Void
}
var responseMapping = [ResponseMap]()
let promise1 = Promise<Response>()
let promise2 = Promise<Response1>()
let map1 = ResponseMap(fulfill: promise1.fulfill)
let map2 = ResponseMap(fulfill: promise2.fulfill)
responseMapping.append(map1)
responseMapping.append(map2)