【发布时间】:2018-05-15 06:42:45
【问题描述】:
我使用ObjectMapper有一段时间了,我发现使用文档中描述的方式为具有大量属性的类编写映射函数很麻烦:
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 数据和我的类具有完全相同的属性名称:
func mapping(map: Map) {
let names = Mirror(reflecting: self).children.flatMap { $0.label }
for name in names {
self.value(forKey: name) <- map[name]
}
}
更新:
根据 Sweeper 的回答,我更新了我的代码:
func mapping(map: Map) {
for child in Mirror(reflecting: self).children.compactMap({$0}) {
child <- map[child.label]
}
}
我想这应该可行。
更新 2:
感谢 Sweeper,我发现我最初的猜测是错误的,Child 只是一个 touple 的类型别名:
public typealias Child = (label: String?, value: Any)
所以我的第二次尝试也行不通。
【问题讨论】:
-
您知道在 Swift 4 中您可以使用
Codable并在您的特定情况下为您处理一切吗? -
我知道
Codable,但 ObjectMapper 提供了更多功能,所以我更喜欢只使用它。 -
我更喜欢 github.com/Ahmed-Ali/JSONExport 创建可映射的 swift 类
标签: ios swift reflection objectmapper