-1

I have a method in my Model class that has signature below:

func parse<T: Codable>(data: Data) throws -> Array<T>?

When I call the method in another class, Facade, I get the

Generic Parameter T could not be inferred

Calling function as below

if let data = data {
                do{
                    let parsedArray = try self.model.parse(data: data);
                }
                catch{
                    print(error)
                }

gives me the compiler warning on the line where I call the parse function.

nora
  • 57
  • 7
noobsmcgoobs
  • 2,716
  • 5
  • 32
  • 52
  • you need to explicitly declare the type of the variable you are setting or add another parameter to the parse method and pass the desired type – Leo Dabus Sep 25 '18 at 22:51
  • 2
    `let parsedArray: [YourType] = try model.parse(data: data)` or `let parsedArray = try model.parse(data: data) as [YourType]` – Leo Dabus Sep 25 '18 at 22:52
  • 1
    @LeoDabus please put as an answer and I will accept. To be explicit, the type would be the concrete type not T. – noobsmcgoobs Sep 25 '18 at 23:10
  • note that your parse method should throw or return an optional not both – Leo Dabus Sep 26 '18 at 00:30
  • @LeoDabus thanks for the tip. I will accept the answer below, but how would I get back a type that is generic? For instance, in the above example, get back a generic to type later? Is there a way to do this in Swift? – noobsmcgoobs Sep 26 '18 at 03:53
  • I think you might be interest in this question also https://stackoverflow.com/a/47544741/2303865 – Leo Dabus Sep 26 '18 at 04:01

1 Answers1

1

You need to explicitly declare the type of the variable you are setting or add another parameter to the parse method and pass the desired type:

let parsedArray: [YourType] = try model.parse(data: data)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571