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

Does AlamofireObjectMapper / ObjectMapper support struct type mapping

我正在使用 AlamofireObjectMapper to parse json response to my object. The AlamofireObjectMapper is a extension of ObjectMapper

根据他们的文档,我的模型 class 必须符合 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 协议,我的模型 class 必须为每个字段实现所需的初始化器和映射函数。有道理。

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 类型?那么如何使用它们解析 json 对 struct 类型对象的响应呢?

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

BaseMappable 协议是这样定义的,因此您应该声明每个方法以符合 Mappable.

/// BaseMappable should not be implemented directly. Mappable or StaticMappable should be used instead
public protocol BaseMappable {
    /// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process.
    mutating func mapping(map: Map)
}

可映射协议是这样定义的

public protocol Mappable: BaseMappable {
    /// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point
    init?(map: Map)
}

您必须相应地实施它:

struct Coordinate: Mappable {
    var xPos: Int?
    var yPos: Int?
    
    init?(_ map: Map) {
    }

    mutating func mapping(map: Map) {
        xPos <- map["xPos"]
        yPos <- map["yPos"]
    }
}

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
    }
}

构造函数无法标记为必需,因为结构无法被继承。映射函数必须标记为变异,因为变异结构中存储的数据...