目前我正在使用这段代码来处理解码一些数据:
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
}
有没有办法创建一个泛型方法,将所有这些重复的代码联系在一起?
private func parse(_ data: Data, using decoder: /*Something*/) throws -> [ParsedType]
{
let parsed = try decoder.decode([ParsedType].self, from: data)
return parsed
}
如果你看一下JSONEncoder和PropertyListDecoder的swift stdlib,你会发现它们都共享一个方法
func decode<T: Decodable >(_ type: T.Type, from data: Data) throws -> T
因此,您可以创建一个具有所述方法的协议,并使两个解码器都符合它:
protocol DecoderType {
func decode<T: Decodable >(_ type: T.Type, from data: Data) throws -> T
}
extension JSONDecoder: DecoderType { }
extension PropertyListDecoder: DecoderType { }
并像这样创建您的通用解析函数:
func parseData(_ data: Data, with decoder: DecoderType) throws -> [ParsedType] {
return try decoder.decode([ParsedType].self, from: data)
}
Decodable+Generic.swift
import Foundation
// Generic decode method for Decodable
func decode<T: Decodable>(data: Data) throws -> T {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
}
可解码+通用测试.swift
import XCTest
@testable import YourProject
class Decodable_EncodableTests: XCTestCase {
func testDecodableEncodable() {
struct User: Decodable, Encodable {
let name: String
let sex: String
}
let json = """
{
"name": "Ronaldo",
"sex": "Female"
}
""".data(using: .utf8)!
do {
// When
let name = "Ronaldo"
let sex = "Female"
let user: User = try decode(data: json)
// Then
XCTAssertEqual(user.name, name)
XCTAssertEqual(user.sex, sex)
} catch let error {
XCTFail(error.localizedDescription)
}
}
}