I'm trying to create a generic function in RequestManager that convert the received JSON from server to the specified type through the ServiceManager. This is my code:
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")
}
}
}
}
}
On the line RequestManager.getObject<User> ... I'm getting this error:
Cannot explicitly specialise a generic type
So what did I miss here?
The problem was solved thanks to luk2302
Update Any idea how to improve this code maybe or make it more clean! NB: This is not an issue it's just about good programming habits