-1

I have a git repository of an app that has been working properly and is available on iTunes. I recently wanted to add some updates to it and imported the project into xCode 10. When I tried to build the solution, I get an error "Generic parameter 'T' could not be inferred"

I have tried to update all the pods that are being used.

Here is the code with the error

static func toJSON<T>(_ data: [T]) -> NSArray {
    let encoded = try! JSONEncoder().encode(data)
    let jsonObject = try! JSONSerialization.jsonObject(with: encoded,
                                                       options: []) as! NSArray
    return jsonObject
}

and the error seems to appear on this line

let encoded = try! JSONEncoder().encode(data)

I am very new to Swift and only inherited this project so I am unsure as to what my approach should be in resolving this issue. I've looked through other questions but could not see a solution that would work for me.

Artur L
  • 37
  • 7

1 Answers1

0

The generic parameter T must be constrained to Encodable and please use swiftier code and throw potential errors

static func toJSON<T : Encodable>(_ data: [T]) throws -> [Any] {
    let encoded = try JSONEncoder().encode(data)
    return try JSONSerialization.jsonObject(with: encoded) as! [Any]
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • I tried the suggested approach and the original error is gone, now I am getting the following: Call can throw, but it is not marked with 'try' and the error is not handled. Where should I add the catch? – Artur L Aug 23 '19 at 12:40
  • You have to call the method with `try toJSON...` wrapped in a `try - catch` block. – vadian Aug 23 '19 at 15:42