gpt4 book ai didi

ios - 使用 api 响应(使用 Gloss)更新存储的用户模型,而无需逐行更新每个键

转载 作者:行者123 更新时间:2023-11-28 08:03:21 25 4
gpt4 key购买 nike

我正在使用以下类结构:

import Gloss

class LMSUser: BaseResponse {

public var userId:String?
public var firstName:String?
public var middleName:String?
public var lastName:String?
public var email:String?
public var phone:String?
public var token:String?
public var roles:[String]?

required init?(json: JSON) {
super.init(json: json)
self.userId = "userId" <~~ json
self.firstName = "firstName" <~~ json
self.middleName = "middleName" <~~ json
self.lastName = "lastName" <~~ json
self.email = "email" <~~ json
self.phone = "phone" <~~ json
self.token = "token" <~~ json
self.roles = "roles" <~~ json
self.postInit()
}

public func postInit() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.appUser = self
UserDefaults.standard.set(self.toJSON(), forKey: String.kDeviceUser)
UserDefaults.standard.synchronize()
}

override func toJSON() -> JSON? {
return jsonify([
super.toJSON(),
"userId" ~~> self.userId,
"firstName" ~~> self.firstName,
"middleName" ~~> self.middleName,
"lastName" ~~> self.lastName,
"email" ~~> self.email,
"phone" ~~> self.phone,
"token" ~~> self.token,
"roles" ~~> self.roles,
])
}
}

假设它是一个单例类并且其中有更多变量,并且 api 不会每次都提供完整的细节。我所做的只是逐行手动更新每个字段。谁能帮我省下几行代码?

最佳答案

你可以在你的类中使用一个方法 initUserData 来初始化可用的数据,并为你写的行:)

示例代码:

import Gloss

class LMSUser: BaseResponse {

public var userId:String?
public var firstName:String?
public var middleName:String?
public var lastName:String?
public var email:String?
public var phone:String?
public var token:String?

required init?(json: JSON) {
super.init(json: json)
self.initUserData(json: json)
self.postInit()
}

public func initUserData(json: JSON) {
let vUserID:String? = "userId" <~~ json
if vUserID != nil {
self.userId = vUserID
}

let vFirstName:String? = "firstName" <~~ json
if vFirstName != nil {
self.firstName = vFirstName
}

let vMiddleName:String? = "middleName" <~~ json
if vMiddleName != nil {
self.middleName = vMiddleName
}

let vLastName:String? = "lastName" <~~ json
if vLastName != nil {
self.lastName = vLastName
}

let vEmail:String? = "email" <~~ json
if vEmail != nil {
self.email = vEmail
}

let vPhone:String? = "phone" <~~ json
if vPhone != nil {
self.phone = vPhone
}

let vToken:String? = "token" <~~ json
if vToken != nil {
self.token = vToken
}
}

public func postInit() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.appUser = self
}

override func toJSON() -> JSON? {
return jsonify([
super.toJSON(),
"userId" ~~> self.userId,
"firstName" ~~> self.firstName,
"middleName" ~~> self.middleName,
"lastName" ~~> self.lastName,
"email" ~~> self.email,
"phone" ~~> self.phone,
"token" ~~> self.token
])
}
}

关于ios - 使用 api 响应(使用 Gloss)更新存储的用户模型,而无需逐行更新每个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45913839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com