0

我正在尝试从 UserDefault 获取可散列的自定义对象。我的自定义模型定义如下:

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"]
    }
 }

我的用户默认方法是:

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
    }

我这样称呼它:

UserDefault.getModel(key: "workerProfile")

调用此方法时应用程序崩溃我不明白原因,错误是:

error: generic parameter 'T' could not be inferred
4

1 回答 1

0

我正在回答我自己的问题,如果它对将来的任何人有帮助。它在解码时崩溃,因为 userdefault 中没有值。

由于强制转换,这条线出现了问题:

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

我改变了这个方法:

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
    }

对此:

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
        }
    }
于 2020-04-08T13:39:30.490 回答