Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic types error : Cannot explicitly specialise a generic type

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

like image 652
Chlebta Avatar asked Mar 01 '26 09:03

Chlebta


1 Answers

Compare https://stackoverflow.com/a/35372990/2442804 - you are not allowed to specify the type constraint "by hand". You have to make the compiler infer it. Do that via:

RequestManager.getObject(endpoint: "users/\(userId)") { (user : User?, error) in 
    // ... your normal code
like image 121
luk2302 Avatar answered Mar 03 '26 03:03

luk2302