重学Swift第十篇:Codable

本文深入探讨Swift中的Codable协议,重点解析JSONDecoder的工作原理。通过源码分析,阐述了解码过程中KeyedDecodingContainer的角色,以及JSONDecoder如何利用_JSONDecodingStorage管理和操作解码容器。同时,文章也简要介绍了编码过程,指出编码与解码的逻辑相似性。
摘要由CSDN通过智能技术生成

Codable可以将自身与外部表示形式(例如JSON)进行互相转换的类型。

public protocol Encodable {
   
	func encode(to encoder: Encoder) throws
}
public protocol Decodable {
   
	init(from decoder: Decoder) throws
}
public typealias Codable = Decodable & Encodable

从上可以看到Codable是Decodable和Encodable协议组合的别名。在这两个协议方法中主要涉及Decoder和Encoder两个协议。

解码

public protocol Decoder {
   
	var codingPath: [CodingKey] {
    get }  //CodingKey协议值可为Int或String
	var userInfo: [CodingUserInfoKey : Any] {
    get } //CodingUserInfoKey协议遵守RawRepresentable、Equatable、Hashable协议
	func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey   //字典形式
	func unkeyedContainer() throws -> UnkeyedDecodingContainer //数组形式
	func singleValueContainer() throws -> SingleValueDecodingContainer //原始单值
}

这里来看下KeyedDecodingContainer

public protocol KeyedDecodingContainerProtocol {
   
	associatedtype Key : CodingKey
	var codingPath: [CodingKey] {
    get }
	var allKeys: [Self.Key] {
    get }
	func contains(_ key: Self.Key) -> Bool
	func decode(.............) //代指decode相关方法
}
public struct KeyedDecodingContainer<K> : KeyedDecodingContainerProtocol where K : CodingKey {
   
	public typealias Key = K
	public init<Container>(_ container: Container) where K == Container.Key, Container : KeyedDecodingContainerProtocol
	public var codingPath: [CodingKey] {
    get }
	public var allKeys: [KeyedDecodingContainer<K>.Key] {
    get }
	public func contains(_ key: KeyedDecodingContainer<K>.Key) -> Bool
	func decode(....
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值