【问题标题】:Does AlamofireObjectMapper / ObjectMapper support struct type mappingAlamofireObjectMapper / ObjectMapper 是否支持结构类型映射
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      相关资源
      最近更新 更多