ObjectMapper:在映射函数中使用反射

ObjectMapper: Using reflection in map function

我使用 ObjectMapper 有一段时间了,我发现使用文档中描述的方式为 classes 编写具有大量 属性 的映射函数很麻烦:

func mapping(map: Map) {
    username    <- map["username"]
    age         <- map["age"]
    weight      <- map["weight"]
    array       <- map["array"]
    dictionary  <- map["dictionary"]
    bestFriend  <- map["bestFriend"]
    friends     <- map["friends"]
}

我想知道是否可以使用反射来编写如下所示的映射函数,假设我的 JSON 数据和我的 class 具有完全相同的 属性 名称:

func mapping(map: Map) {
    let names = Mirror(reflecting: self).children.flatMap { [=11=].label }
    for name in names {
        self.value(forKey: name) <- map[name]
    }
}

更新:

根据 Sweeper 的回答我更新了我的代码:

func mapping(map: Map) {
    for child in Mirror(reflecting: self).children.compactMap({[=12=]}) {
        child <- map[child.label]
    }
}

我想这应该可行。

更新 2:

感谢 Sweeper,我发现我最初的猜测是错误的,Child 只是一个双元组的类型别名:

public typealias Child = (label: String?, value: Any)

所以我的第二次尝试也不行。

<- 运算符声明如下:

public func <- <T: RawRepresentable>(left: inout T, right: Map) {
    left <- (right, EnumTransform())
}

如您所见,左侧参数已声明 inout。这意味着您必须在那里使用可变变量,而不是某些方法的 return 值。

所以你确实需要写所有的属性。

我找到了这个为您生成映射的插件:https://github.com/liyanhuadev/ObjectMapper-Plugin

在 Swift 4 中,引入了 Codable,但它会自动为您解决问题:

struct Foo: Codable {
    var username: String
    var age: Int
    var weight: Double

    // everything is done for you already! You don't need to write anything else
}