美文网首页iOS-Swift
swift字典转模型,数组转模型数组

swift字典转模型,数组转模型数组

作者: lzy_iOS | 来源:发表于2019-01-23 18:14 被阅读0次

/// 字典转模型

///

/// - Parameters:

///  - type: 模型类型

///  - data: 字典

/// -Returns: 模型

/// -Throws: 抛出异常关键字

funcJSONModel(_type:T.Type, withKeyValues data:[String:Any])throws->TwhereT:Decodable{

    letjsonData =tryJSONSerialization.data(withJSONObject: data, options: [])

    letmodel =tryJSONDecoder().decode(type, from: jsonData)

    returnmodel

}

/// 数组转模型

///

/// - Parameters:

///  - type: 模型类型

///  - datas: 字典数组

/// -Returns: 模型数组

/// -Throws: 抛出异常关键字

funcJSONModel(_type:T.Type, withKeyValuesArray datas: [[String:Any]])throws-> [T]  whereT:Decodable{

    vartemp: [T] = []

    fordataindatas {

        letmodel =tryJSONModel(type, withKeyValues: data)

        temp.append(model)

    }

    returntemp

}

相关文章

网友评论

    本文标题:swift字典转模型,数组转模型数组

    本文链接:https://www.haomeiwen.com/subject/zresjqtx.html