创建实现 Mappable 接口的对象的新实例

Creating new instance of object implementing Mappable interface

我正在使用 ObjectMapper library 将我的模型对象(classes 和结构)与 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)

以这种方式创建对象是否可以 class 实现 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)