JSONCodable icon indicating copy to clipboard operation
JSONCodable copied to clipboard

Issues with Arrays

Open pronebird opened this issue 9 years ago • 1 comments

I have a structure called OTKSession that conforms to JSONDecodable, however using in it context of Array within generics does not work and I get the following error:

Client.swift:128:19: In argument type '(Result<[OTKSession]>) -> Void', '[OTKSession]' does not conform to expected type 'JSONDecodable'

Example code:

func rest<ResponseType: JSONDecodable>(_ completionHandler: @escaping (Result<ResponseType>) -> Void) {
  let value = ... // comes asynchronously
  let jsonString = String(bytes: value.0, encoding: .utf8)!
  let responseObject = try! ResponseType(JSONString: jsonString)
  completionHandler(.ok(responseObject))
}

Do I have to handle arrays separately or it is possible to incorporate them within single function? It seems like there is no way to constraint generics to Array of JSONDecodable objects.

At the moment I've added overloaded method that wraps ResponseType in array. Two methods coexist just fine but it seems like a code duplication to me which probably can be solved in more elegant way.

func rest<ResponseType: JSONDecodable>(_ completionHandler: @escaping (Result<[ResponseType]>) -> Void) {
  let value = ... // comes asynchronously
  let jsonString = String(bytes: value.0, encoding: .utf8)!
  let responseObject = try! [ResponseType](JSONString: jsonString)
  completionHandler(.ok(responseObject))
}

pronebird avatar Dec 29 '16 16:12 pronebird

Hi thanks for asking, but unfortunately I do not have a good answer to this.. In fact we are handling similar cases like this within the JSONCodable library itself.

Nadohs avatar Jan 15 '17 00:01 Nadohs