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

15

我正在使用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"]
    }
}
为了符合可映射协议,我的模型类必须实现所需的初始化程序和每个字段的映射函数。这是有道理的。但是,它如何支持结构类型?例如,我有一个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符合可映射性。

(我认为使用struct来处理坐标数据而不是使用class是非常常见的)

我的问题:

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

Q2. 如果这些库不支持将json响应解析为结构体类型的对象。 iOS中用Swift2实现此操作的方法是什么?

1个回答

12

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接