文章目录
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(....