【发布时间】:2016-09-09 08:11:03
【问题描述】:
我正在使用AlamofireObjectMapper 来解析对我的对象的 json 响应。 AlamofireObjectMapper 是ObjectMapper 的扩展。
根据他们的文档,我的模型类必须符合Mappable 协议。例如:
class Forecast: Mappable {
var day: String?
var temperature: Int?
var conditions: String?
required init?(_ map: Map){
}
func mapping(map: Map) {
day <- map["day"]
temperature <- map["temperature"]
conditions <- map["conditions"]
}
}
为了符合 Mappable protocl,我的模型类必须为每个字段实现所需的初始化程序和映射函数。有道理。
BUT,它是如何支持struct类型的?比如我有一个Coordinate结构,我尝试符合Mappable协议:
struct Coordinate: Mappable {
var xPos: Int
var yPos: Int
// ERROR: 'required' initializer in non-class type
required init?(_ map: Map) {}
func mapping(map: Map) {
xPos <- map["xPos"]
yPos <- map["yPos"]
}
}
由于上面显示的错误,我无法使我的 Coordinate 符合 Mappable。
(我认为经常使用struct 来获取坐标数据而不是使用class)
我的问题:
Q1. AlamofireObjectMapper 或 ObjectMapper 库是否支持struct 类型?那么如何使用它们解析对struct类型对象的json响应呢?
Q2. 如果这些库不支持将 json 响应解析为结构类型对象。在 iOS 中使用 Swift2 的方法是什么?
【问题讨论】:
标签: ios swift swift2 alamofire objectmapper