自定义 Swift Codable 编码器和解码器

1,557 阅读1分钟

自定义 Swift Codable 编码器和解码器

作者 Mattt

在 Swift 4 中声明了 Codable 协议的类型实现 EncoderDecoder 之后, 都可以同其表示进行编解码操作。

这个功能发布之初, 只有 Foundation 框架中的 JSONEncoder / JSONDecoder / PropertyListEncoder /PropertyListDecoder 有相关的功能实现。然而这些类型的实现细节还和 JSONSerializationPropertyListSerialization 混杂在一起。

我们在 GitHub 上发布的 DIY Codable Encoder / Decoder Kit 让开发者为自定义格式添加编码解码器更方便了。代码模版中包含所需类型和方法的占位符,同时也包含编码和解码 Codable 类型的简单测试。

简单替换掉 Format 的名字,然后重命名文件,你自己的格式也可以方便地实现它们。

编码器结构

public class <#Format#>Encoder {
    public func encode<T>(_ value: T) throws -> Data
                        where T : Encodable
}

class _<#Format#>Encoder: Encoder {
    class SingleValueContainer: SingleValueEncodingContainer
    class UnkeyedContainer: UnkeyedEncodingContainer
    class KeyedContainer<Key>: KeyedEncodingContainerProtocol
            where Key: CodingKey
}

protocol <#Format#>EncodingContainer: class {}

解码器结构

public class <#Format#>PackDecoder {
    public func decode<T>(_ type: T.Type,
                          from data: Data) throws -> T
                        where T : Decodable
}

final class _<#Format#>Decoder: Decoder {
    class SingleValueContainer: SingleValueDecodingContainer
    class UnkeyedContainer: UnkeyedDecodingContainer
    class KeyedContainer<Key>: KeyedContainer
            where Key: CodingKey
}

protocol <#Format#>DecodingContainer: class {}

Codable 的 MessagePack 编码解码器 中有使用这个模版的样例代码可以参考。

希望大家能够喜欢这个项目。欢迎大家来我们的 Twitter 与大家交流你自己实现的自定义编码器和解码器。

学习了解更多关于 Codable 的知识, 请参阅 使用 Swift Codable 进行高效的数据编解码