如果我有一个符合
如何创建一个编码器和解码器,将其编码/解码为
注意:我知道在将结果转换为字典对象之前可以使用JSONEncoder和JSONDecoder类,但出于效率原因,我不想这样做。
Swift标准库自带JSONEncoder、JSONDecoder、PListEncoder和PListDecoder类,它们都符合Encoder和Decoder协议。
我的问题是,我不知道如何为我的自定义编码器和解码器类实现这些协议。
鉴于Swift是开源的,可以查看标准库中JSONEncoder和PListEncoder类的源代码,但源文件很大且缺乏文档,除了一些注释外,很难理解。
Codable
协议的结构体,像这样:enum AnimalType: String, Codable {
case dog
case cat
case bird
case hamster
}
struct Pet: Codable {
var name: String
var animalType: AnimalType
var age: Int
var ownerName: String
var pastOwnerName: String?
}
如何创建一个编码器和解码器,将其编码/解码为
Dictionary<String, Any?>
类型的实例?let petDictionary: [String : Any?] = [
"name": "Fido",
"animalType": "dog",
"age": 5,
"ownerName": "Bob",
"pastOwnerName": nil
]
let decoder = DictionaryDecoder()
let pet = try! decoder.decode(Pet.self, for: petDictionary)
注意:我知道在将结果转换为字典对象之前可以使用JSONEncoder和JSONDecoder类,但出于效率原因,我不想这样做。
Swift标准库自带JSONEncoder、JSONDecoder、PListEncoder和PListDecoder类,它们都符合Encoder和Decoder协议。
我的问题是,我不知道如何为我的自定义编码器和解码器类实现这些协议。
class DictionaryEncoder: Encoder {
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey : Any]
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
}
func singleValueContainer() -> SingleValueEncodingContainer {
}
}
class DictionaryDecoder: Decoder {
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey : Any]
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey {
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
}
}
鉴于Swift是开源的,可以查看标准库中JSONEncoder和PListEncoder类的源代码,但源文件很大且缺乏文档,除了一些注释外,很难理解。
Encoder
和Decoder
协议,您可以实现它们来为Codable协议创建自己的自定义编码器和解码器。Swift标准库附带了两个这样的编码器/解码器对: https://github.com/apple/swift/blob/master/stdlib/public/SDK/Foundation/PlistEncoder.swift https://github.com/apple/swift/blob/master/stdlib/public/SDK/Foundation/JSONEncoder.swift - Toni SučićEncoder
和Decoder
协议的自定义编码器和解码器。 - Toni Sučić