请考虑以下协议定义和2个实现该协议的结构。
protocol Response: Decodable {
associatedtype T: Decodable
var info: T? { get }
}
struct Response1<T: Decodable>: Response {
let info: T?
}
struct Response2<T: Decodable>: Response {
let info: T?
}
以下是用于转换Response
协议实例的通用结构。
struct Result<T: Decodable> {
let info: T?
init<U: Response>(response: U) where U.T == T {
self.info = response.info
}
}
以下函数编译成功。
func function<U, V: Response>(type: V.Type) -> Result<U> where U == V.T {
let response = try! JSONDecoder().decode(type, from: Data())
return Result(response: response)
}
我想为该参数添加默认参数,如下所示。
func function<U, V: Response>(type: V.Type = Response1<U>.self) -> Result<U> where U == V.T {
let response = try! JSONDecoder().decode(type, from: Data())
return Result(response: response)
}
以上代码的编译失败,并显示错误-
类型'Response1.Type'的默认参数值不能转换为类型'V.Type'
谁能指出解决此问题的方法?