gpt4 book ai didi

ios - 初始化对象的多种方法?

转载 作者:行者123 更新时间:2023-11-28 12:16:30 24 4
gpt4 key购买 nike

我有一个将 init 与 JSON 结合使用的模型,因此我可以直接从 API 响应创建对象。

但是在这种情况下,我想初始化模型并手动输入其属性,因此它不会是 JSON。

我怎样才能有另一个初始化方法,让我不使用标准的 JSON 方法,而是手动输入我的参数?

模型看起来像这样......

class Conversation: NSObject {

var id: String
var index: String
var image: String
var firstname: String
var lastname: String
var withuserid: String
var badgeCount: String

init?(_ json: JSON) {
guard let id = json["id"].string,
let index = json["index"].string,
let image = json["image"].string,
let firstname = json["firstname"].string,
let lastname = json["lastname"].string,
let withuserid = json["withuserid"].string,
let badgeCount = json["badgeCount"].string

else { return nil }

self.id = id
self.index = index
self.image = image
self.firstname = firstname
self.lastname = lastname
self.withuserid = withuserid
self.badgeCount = badgeCount
}
}

最佳答案

只需添加另一个 init,因为您可以为一个 structclass 添加多个,然后调用所需的:

class Conversation: NSObject {
var id: String
var index: String
var image: String
var firstname: String
var lastname: String
var withuserid: String
var badgeCount: String

init?(_ json: JSON) {
guard let id = json["id"].string,
let index = json["index"].string,
let image = json["image"].string,
let firstname = json["firstname"].string,
let lastname = json["lastname"].string,
let withuserid = json["withuserid"].string,
let badgeCount = json["badgeCount"].string

else { return nil }

self.id = id
self.index = index
self.image = image
self.firstname = firstname
self.lastname = lastname
self.withuserid = withuserid
self.badgeCount = badgeCount
}

init(id: String, index: String, image: String, firstName: String, lastName: String, withUserId: String, badgeCount: String) {
self.id = id
self.index = index
self.image = image
self.firstName = firstName
self.lastName = lastName
self.withUserId = withUserId
self.badgeCount = badgeCount
}
}

关于ios - 初始化对象的多种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46339442/

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