gpt4 book ai didi

swift - 泛型类型错误 : Cannot explicitly specialise a generic type

转载 作者:可可西里 更新时间:2023-11-01 00:57:08 25 4
gpt4 key购买 nike

我正在尝试在 RequestManager 中创建一个通用函数通过 ServiceManager 将服务器接收到的 JSON 转换为指定类型.这是我的代码:

请求管理器:

typealias ResultResponseManager  = (_ data: AnyObject?, _ error: ErrorPortage?) -> Void
typealias SuccessResponseManager = (_ success: Bool, _ error: ErrorPortage?) -> Void
typealias objectBlock<T:GenericModel> = (_ object: T?, _ error: ErrorPortage?) -> Void

extension RequestManager {

static func getObject<T: GenericModel>(endpoint: String, completionBlock: objectBlock<T>? = nil){

RequestHelper(url: "\(getAPIURL())\(endpoint))")
.performJSONLaunchRequest { (result, error) in

if let result = result as? NSDictionary,
error == nil {
let object = T(dic: result)
completionBlock?(object, nil)
}
else {
completionBlock?(nil, error)
}
}
}


}

服务管理器:

typealias ObjectResult =  (GenericModel?, ErrorPortage?) -> Void
typealias ObjectsResult = ([GenericModel]?, ErrorPortage?) -> Void

extension ServiceManager {

static func getUser(_ id: Int? = nil, _ completion: ObjectResult? = nil) {

guard let userId: Int = id ?? UserManager.shared.userId else {

return
}

RequestManager.getObject<User>(endpoint: "users/\(userId)") { (user, error) in
if user = user {

//update userdefault
if userId == UserManager.shared.userId {
UserDefaults.standard.set(result, forKey: "currentUser")
}
}
}
}
}

在线RequestManager.getObject<User> ...我收到此错误:

Cannot explicitly specialise a generic type

那么我在这里错过了什么?

The problem was solved thanks to luk2302

更新知道如何改进此代码或使其更干净!注意:这不是问题,这只是良好的编程习惯

最佳答案

比较 https://stackoverflow.com/a/35372990/2442804 - 不允许“手动”指定类型约束。你必须让编译器推断它。通过以下方式做到这一点:

RequestManager.getObject(endpoint: "users/\(userId)") { (user : User?, error) in 
// ... your normal code

关于swift - 泛型类型错误 : Cannot explicitly specialise a generic type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44064245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com