Swift 之 Codable

自从Swift 4.0 之后取代HandyJSON 的原生解析model 的类

关于 官方文档

/// A type that can convert itself into and out of an external representation.
///
/// `Codable` is a type alias for the `Encodable` and `Decodable` protocols.
/// When you use `Codable` as a type or a generic constraint, it matches
/// any type that conforms to both protocols.
public typealias Codable = Decodable & Encodable

复制代码

Codable 是一个可以编码 和解码的 协议 当你使用Codable 做为一个类型或 泛型约束 它可以匹配任何 符合协议的类型

用法

Model

struct AutionListModel: Codable {
	let status: Int
	let message: String
	let data: [Datum]
}

struct Datum: Codable {
	let sheng, projectID, projectType, status: Int
	let nowMoney: String
	let project: Project
	let shi: Int
	let updatedAt, endTime, openingBid: String
	let type, participation, id, xian: Int
	let jiaoTime: String
	let yanNum, yanQi: Int
	let randNum: JSONNull?
	let cashDeposit: String
	let winID: Int?
	let deadline, closingCost, markUp, startTime: String
	let xiang: Int
	let createdAt: String
	let lookNum: Int
	
	enum CodingKeys: String, CodingKey {
		case sheng
		case projectID = "projectId"
		case projectType, status, nowMoney, project, shi
		case updatedAt = "updated_at"
		case endTime, openingBid, type, participation, id, xian, jiaoTime, yanNum, yanQi, randNum, cashDeposit
		case winID = "winId"
		case deadline, closingCost, markUp, startTime, xiang
		case createdAt = "created_at"
		case lookNum
	}
}

struct Project: Codable {
	let xian, title: String
	let thumb: String
	let lookNum: Int
	let sheng, juli: String
}

有些字段可能为空值 所以不确定是否有值的时候声明为可选值(?)

复制代码

自定义键名

当后台返回的字段和系统关键字冲突的时候 或者key 不匹配的时候

enum CodingKeys: String, CodingKey {
		case sheng
		case projectID = "projectId"
		case projectType, status, nowMoney, project, shi
		case updatedAt = "updated_at"
		case endTime, openingBid, type, participation, id, xian, jiaoTime, yanNum, yanQi, randNum, cashDeposit
		case winID = "winId"
		case deadline, closingCost, markUp, startTime, xiang
		case createdAt = "created_at"
		case lookNum
	}

复制代码

不确定数据类型的解析

声明一个跨类型解析类TStrInt: 新手 我也没太懂 怎么回事

一个含有int,string的类,可用于解析后台返回类型不确定的字段。

即:把int\string解析成TStrInt且解析后TStrInt的int和string都有值

struct TStrInt: Codable {
    var int:Int {
        didSet {
            let stringValue = String(int)
            if  stringValue != string {
                string = stringValue
            }
        }
    }
    
    var string:String {
        didSet {
            if let intValue = Int(string), intValue != int {
                int = intValue
            }
        }
    }
    
    //自定义解码(通过覆盖默认方法实现)
    init(from decoder: Decoder) throws {
        let singleValueContainer = try decoder.singleValueContainer()
        
        if let stringValue = try? singleValueContainer.decode(String.self)
        {
            string = stringValue
            int = Int(stringValue) ?? 0
            
        } else if let intValue = try? singleValueContainer.decode(Int.self)
        {
            int = intValue
            string = String(intValue);
        } else
        {
            int = 0
            string = ""
        }
    }
}
复制代码

猜你喜欢

转载自blog.csdn.net/weixin_33755649/article/details/91364780