AlamofireObjectMapper/ObjectMapper是否支持结构类型映射

Lee*_*fin 10 ios swift alamofire swift2 objectmapper

我正在使用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"]
    }
}
Run Code Online (Sandbox Code Playgroud)

为了符合Mappable protocl,我的模型类必须为每个字段实现所需的初始化器和映射函数.这说得通.

但是,它如何支持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"]
    }
}
Run Code Online (Sandbox Code Playgroud)

Coordinate由于上面显示的错误,我无法使我符合Mappable.

(我认为通常使用struct坐标数据而不是使用class)

我的问题:

Q1.AlamofireObjectMapper或ObjectMapper库是否支持struct类型?如何使用它们解析json对struct类型对象的响应呢?

Q2.如果这些库不支持解析对struct类型对象的json响应.使用Swift2在iOS中这样做的方法是什么?

JMI*_*JMI 7

可映射协议定义如下

public protocol Mappable {
    init?(_ map: Map)
    mutating func mapping(map: Map)
}
Run Code Online (Sandbox Code Playgroud)

你必须相应地实现它:

struct Coordinate: Mappable {
    var xPos: Int?
    var yPos: Int?

    init?(_ map: Map) {
    }

    mutating func mapping(map: Map) {
        xPos <- map["xPos"]
        yPos <- map["yPos"]
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

struct Coordinate: Mappable {
    var xPos: Int
    var yPos: Int

    init?(_ map: Map) {
    }

    mutating func mapping(map: Map) {
        xPos <- map["xPos"] ?? 0
        yPos <- map["yPos"] ?? 0
    }
}
Run Code Online (Sandbox Code Playgroud)

无法将构造函数标记为必需,因为不能继承struct.映射函数必须标记为变异,因为在结构中改变存储的数据...