【问题标题】:Swift generics issue: generic parameter could not be inferredSwift 泛型问题:无法推断泛型参数
【发布时间】: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。

任何想法如何修复错误?

【问题讨论】:

标签: ios swift generics type-conversion swift4


【解决方案1】:

这是错误的签名:

public func getLoginInfo(loginInfoClass: LoginInfoBase.Type, completionHandler: @escaping (Swift.Result<LoginInfoBase, Error>) -> Void)

你的意思是:

public func getLoginInfo<T: LoginInfoBase>(loginInfoClass: T.Type, completionHandler: @escaping (Swift.Result<LoginInfoBase, Error>) -> Void)
                        ^^^^^^^^^^^^^^^^^^                 ^

您需要将 concrete 类型传递给符合 LoginInfoBase 的getLoginInfo。不只是任何亚型。这与您的 genericQuery 方法匹配。

然后您应该将您对 genericQuery 的调用修改为:

genericQuery(urlString: "\(baseURL)/users/get_login_info/",
             method: .get,
             params: nil,
             decodable: T.self) { ... } // use T.self here.

更多详情请见Alexander's link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 2016-10-11
    • 2010-11-18
    • 1970-01-01
    相关资源
    最近更新 更多