Swift 4中的通用解码器 [英] Generic Decoders in Swift 4
本文介绍了Swift 4中的通用解码器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前,我正在使用此代码来处理一些数据的解码:
Currently I'm using this code to handle decoding some data:
private func parseJSON(_ data: Data) throws -> [ParsedType]
{
let decoder = JSONDecoder()
let parsed = try decoder.decode([ParsedType].self, from: data)
return parsed
}
private func parsePlist(_ data: Data) throws -> [ParsedType]
{
let decoder = PropertyListDecoder()
let parsed = try decoder.decode([ParsedType].self, from: data)
return parsed
}
是否有一种方法可以创建将所有重复代码联系在一起的通用方法?
Is there a way to create a generic method that ties all this repeated code together?
private func parse(_ data: Data, using decoder: /*Something*/) throws -> [ParsedType]
{
let parsed = try decoder.decode([ParsedType].self, from: data)
return parsed
}
推荐答案
如果您查看 JSONEncoder 和 PropertyListDecoder 您会看到它们都共享一个方法
If you look at the swift stdlib for JSONEncoder and PropertyListDecoder you will see that they both share a method
func decode<T: Decodable >(_ type: T.Type, from data: Data) throws -> T
因此,您可以创建一个具有上述方法的协议,并使两个解码器都符合该方法:
So you could create a protocol that has said method and conform both decoders to it:
protocol DecoderType {
func decode<T: Decodable >(_ type: T.Type, from data: Data) throws -> T
}
extension JSONDecoder: DecoderType { }
extension PropertyListDecoder: DecoderType { }
并创建通用解析函数,如下所示:
And create your generic parse function like so:
func parseData(_ data: Data, with decoder: DecoderType) throws -> [ParsedType] {
return try decoder.decode([ParsedType].self, from: data)
}
这篇关于Swift 4中的通用解码器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文