如果我有一个符合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
andJSONDecoder
类,但出于效率原因,我不希望这样做。
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类的源代码,但是由于缺少文档,除了一些注释之外,源文件非常庞大且难以理解。