gpt4 book ai didi

swift - 创建实现 Mappable 接口(interface)的对象的新实例

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:04 25 4
gpt4 key购买 nike

我正在使用 ObjectMapper library将我的模型对象(类和结构)与 JSON 相互转换。

但有时我想创建没有 JSON 的对象。

假设,我有这样的类(class):

class User: Mappable {
var username: String?
var age: Int?

required init?(map: Map) {

}

func mapping(map: Map) {
username <- map["username"]
age <- map["age"]
}
}

我想创建没有 JSON 的对象,如下所示:

let newUser = User(username: "john", age: 18)

对于实现Mappable的类,以这种方式创建对象是否可行?

最佳答案

添加另一个以用户名和年龄作为参数的初始化方法。

class User: Mappable {
var username: String?
var age: Int?

init(username:String, age:Int) {
self.username = username
self.age = age
}

required init?(map: Map) {

}

func mapping(map: Map) {
username <- map["username"]
age <- map["age"]
}
}

然后像这样使用它。

let user = User(username: "hello", age: 34)

关于swift - 创建实现 Mappable 接口(interface)的对象的新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47249067/

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