跳转至

Core-mapArray

/// Response -> [Model]
///
/// - Parameters:
///   - type: 模型类型
///   - modelKey: 模型路径
/// - Returns: 模型数组
func mapArray<T: Modelable>(_ type: T.Type, modelKey: String? = nil) -> [T]

Response 转换为 模型数组 (模型遵守 Modelable 协议)

  • type 遵守了 Modelable 协议的模型类型
  • modelKey 指定取值路径,可以设置多级,如 retBody>name ,如果为 nil ,则取当前 ResponseModelableParameterTypemodelKey

ps: 当前ResponseModelableParameterType 可以通过 MoyaMapperPlugin 进行统一设置


Example

success-array

struct MMModel: Modelable {
    var name : String
    var organization : String
    var logoUrl : String
    var github : String
    var avatar : String
    var author : String
    var age : Int

    init(_ json: JSON) {
        name = json["name"].stringValue
        organization = json["organization"].stringValue
        logoUrl = json["logoUrl"].stringValue
        github = json["github"].stringValue
        avatar = json["avatar"].stringValue
        author = json["author"].stringValue
        age = json["age"].intValue
    }
}

转模型数组

let models = response.mapArray(MMModel.self, modelKey: "retBody")
let name = models[0].name
print("count -- \(models.count)")
print("name -- \(name)")

打印结果

count -- 4
name -- MoyaMapper