【发布时间】:2021-11-06 10:05:26
【问题描述】:
使用此代码:
public protocol LoginInfoBase: Decodable {
var access_token: String? { get }
var notifications: [PushNotification] { get }
}
public class ExampleLoginInfo: LoginInfoBase {
public var access_token: String? = nil
public var notifications: [PushNotification] = []
public var user_info: UserInfo? = nil
public var more_example_data: String? = nil
}
public func genericQuery<T: Decodable>(urlString: String, method: QueryType, params: Parameters?, decodable: T.Type,completionHandler: @escaping (Swift.Result<T, Error>) -> Void) {
<more code here>
}
}
public func getLoginInfo(loginInfoClass: LoginInfoBase.Type, completionHandler: @escaping (Swift.Result<LoginInfoBase, Error>) -> Void) {
genericQuery(urlString: "\(baseURL)/users/get_login_info/", method: .get, params: nil, decodable: loginInfoClass.self) { result in
<more code here>
}
}
然后我打电话给getLoginInfo...
getLoginInfo(loginInfoClass: ExampleLoginInfo.self) { result in
<more code here>
}
...并得到这个错误:
Generic parameter 'T' could not be inferred
Cannot convert value of type 'LoginInfoBase.Type' to expected argument type 'T.Type'
这是背景。我正在尝试设置一个通用登录库,可以使用包含特定于每个应用程序的用户数据的类调用它。在这个应用程序中,我将LoginInfoBase 子类化为ExampleLoginInfo 以添加额外的用户数据.我的意图是该库随后将从服务器返回的用户数据解码为 ExampleLoginInfo。
任何想法如何修复错误?
【问题讨论】:
-
这是“协议不符合自身”问题之一:stackoverflow.com/a/43408193/3141234
标签: ios swift generics type-conversion swift4