I have a superclass for generic parsing
class Converter<T, U> {
func convert(value: T) throws -> U {
preconditionFailure("Converter not implemented")
}
}
class Factory {
required init () { }
var className: String {
return "\( self )"
}
fund responseBodyConverter<T>(type: T.Type) -> Converter<Data, T>? {
return nil
}
}
and have a subclass with Generic type constraint
final class CodableConverter<T>: Converter<Data, T> where T: Decodable {
var jsonDecoder: JSONDecoder
let type: T.Type
init(_ jsonDecoder: JSONDecoder, type: T.Type) {
self.jsonDecoder = jsonDecoder
self.type = type
}
override func convert(value: Data) throws -> T {
do {
return try JSONDecoder().decode(type, from: value)
} catch {
throw error
}
}
}
class CodableConverterFactory: Factory {
static func create() -> CodableConverterFactory {
return CodableConverterFactory()
}
override func responseBodyConverter<T>(type: T.Type) -> Converter<Data, T>? where T: Decodable {
return CodableConverter(JSONDecoder(), type: type.self)
}
}
here try to create a new instance and call override method app crash Thread 1: EXC_BAD_ACCESS (code=1, address=0x8)
but when try to execute the JSONDecoder
in LLDB console using po
command is working
let factory = CodableConverterFactory.create()
let result = factory.responseBodyConverter(type: User.self)
do {
let user = try result?.convert(value: json.data(using: .utf8)!)
print(user)
} catch {
print(error)
}