App Crashing with error: generic parameter 'T' could not be inferred

旧巷老猫 提交于 2020-04-18 05:45:40

问题


I'm trying to get custom object which is hashable from UserDefault. My custom model is defined below:

class WorkerProfileResponse: Mappable, Hashable{

    static func == (lhs: WorkerProfileResponse, rhs: WorkerProfileResponse) -> Bool {
        return lhs.id == rhs.id
    } 
    var hashValue: Int{
        return self.id!
    }
    var id, loginStatus, lastLogin, lastActive: Int?
    var username, email, mobileNumber: String?
    var userCategories: [String]?
    var userSubCategories: [String]?
    var biometricToken: String?
    var accessToken: AccessToken?
    var userStatus: UserStatus?
    var userProfile: UserProfile?

    required init(map: Map) {        
    }

    func mapping(map: Map) {
        id <- map["id"]
        loginStatus <- map["is_logged_in"]
        lastLogin <- map["last_login"]
        lastActive <- map["last_active"]
        biometricToken <- map["biometricToken"]
        username <- map["username"]
        email <- map["email"]
        mobileNumber <- map["mobile_number"]
        accessToken <- map["accessToken"]
        userStatus <- map["userStatus"]
        userCategories <- map["userCategories"]
        userSubCategories <- map["userSubCategories"]
        userProfile <- map["userProfile"]
    }
 }

My userdefault method is:

class func getModel<T: Hashable>(key: String) -> T {
        let decoded  = UserDefaults.standard.data(forKey: key)
        let decodedModel = NSKeyedUnarchiver.unarchiveObject(with: decoded!) as! T
        return decodedModel
    }

And I'm calling it like this:

UserDefault.getModel(key: "workerProfile")

App is crashing when I'm calling this method I don't understand the reason, error is:

error: generic parameter 'T' could not be inferred

回答1:


I'm answering my own question, if it helps anyone in the future. It was crashing while decoding because there was no value present in userdefault.

This line had the issue because of force casting:

let decodedModel = NSKeyedUnarchiver.unarchiveObject(with: decoded!) as! T

I've changes this method:

class func getModel<T: Hashable>(key: String) -> T {
        let decoded  = UserDefaults.standard.data(forKey: key)
        let decodedModel = NSKeyedUnarchiver.unarchiveObject(with: decoded!) as! T
        return decodedModel
    }

To this:

class func getModel<T: Hashable>(key: String) -> T? {
        let decoded  = UserDefaults.standard.data(forKey: key)
        if decoded != nil{
            let decodedModel = NSKeyedUnarchiver.unarchiveObject(with: decoded!) as! T
            return decodedModel
        }
        else
        {
            return nil
        }
    }


来源:https://stackoverflow.com/questions/61100434/app-crashing-with-error-generic-parameter-t-could-not-be-inferred

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!