Swift 实现URL类型的KeyedDecodingContainerProtocol
我正在做一个项目,创建一个自定义的Swift 实现URL类型的KeyedDecodingContainerProtocol,swift,codable,decoder,decodable,encodable,Swift,Codable,Decoder,Decodable,Encodable,我正在做一个项目,创建一个自定义的解码器来处理非JSON数据 要解码的数据可以是URLs或Strings。例如: struct MyData: Decodable { let server: URL let version: String } 为了处理这种类型的解码,我实现了一个名为KeyedContainer的类,它实现了KeyedDecodingContainerProtocol 对于字符串非常简单,因为我可以使用以下方法: func decode(_ type: Stri
解码器
来处理非JSON数据
要解码的数据可以是URL
s或String
s。例如:
struct MyData: Decodable {
let server: URL
let version: String
}
为了处理这种类型的解码,我实现了一个名为KeyedContainer
的类,它实现了KeyedDecodingContainerProtocol
对于字符串
非常简单,因为我可以使用以下方法:
func decode(_ type: String.Type, forKey key: Key) throws -> String { }
相反,对于URL
,我需要依赖以下内容:
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { }
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
try checkCanDecodeValue(forKey: key)
guard let value = configuration[key.stringValue] else {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: "TODO")
throw DecodingError.typeMismatch(type, context)
}
guard let url = URL(string: value) else {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: "TODO")
throw DecodingError.valueNotFound(type, context)
}
return url as! T
}
func decode(utype:T.type,forKey:key)抛出->T其中T:Decodable{}
在它里面,我做了如下的事情:
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { }
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
try checkCanDecodeValue(forKey: key)
guard let value = configuration[key.stringValue] else {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: "TODO")
throw DecodingError.typeMismatch(type, context)
}
guard let url = URL(string: value) else {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: "TODO")
throw DecodingError.valueNotFound(type, context)
}
return url as! T
}
func decode(utype:T.type,forKey:key)抛出->T其中T:Decodable{
尝试CheckCanDevoValue(forKey:key)
保护let值=配置[key.stringValue]其他{
让context=DecodingError.context(codingPath:codingPath,debugDescription:“TODO”)
抛出解码错误。类型不匹配(类型,上下文)
}
guard let url=url(字符串:值)else{
让context=DecodingError.context(codingPath:codingPath,debugDescription:“TODO”)
抛出DecodingError.valueNotFound(类型,上下文)
}
返回url为!T
}
其中,configuration
是直接从自定义解码器传递到KeyedContainer
的结构
这是正确的方法吗?我不确定的是
as!T
强制转换以使编译器满意。可解码的有什么问题?@MojtabaHosseini没有任何问题。我只是想知道你是否可以为URL
建议一种不同的方法。我的意思是你为什么不想使用它?符合可解码并实现自定义解码功能。不清楚您的意思。我需要维护定制解码器@MojtabaHosseini