我正在尝试在RequestManager
中创建一个通用函数,它通过ServiceManager
将收到的JSON从服务器转换为指定的类型。这是我的代码:
RequestManager:
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)
}
}
}
}
ServiceManger:
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> ...
行上我收到此错误:
无法明确专门化泛型类型
那么我在这里想念的是什么?
由于luk2302
,问题解决了
更新 任何想法如何改进这个代码可能或使其更干净! 注意:这不是一个问题,只是关于良好的编程习惯
答案 0 :(得分:3)
比较https://stackoverflow.com/a/35372990/2442804 - 您不允许“手动”指定类型约束。你必须让编译器推断它。通过以下方式做到:
RequestManager.getObject(endpoint: "users/\(userId)") { (user : User?, error) in
// ... your normal code