【问题标题】:Creating new instance of object implementing Mappable interface创建实现 Mappable 接口的对象的新实例
【发布时间】:2018-04-25 05:37:30
【问题描述】:

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

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

假设,我有这样的课:

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的类是否可以以这种方式创建对象?

【问题讨论】:

    标签: swift swift3 objectmapper


    【解决方案1】:

    添加另一个以用户名和年龄为参数的 init 方法。

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      相关资源
      最近更新 更多