Skip to content

Issues with Arrays #70

@pronebird

Description

@pronebird

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))
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions