Swift 4: With Codable `Generic parameter 'T' could not be inferred`
Asked Answered
W

1

12

I am getting the following error:

Generic parameter 'T' could not be inferred

on line: let data = try encoder.encode(obj)

Here is the code

import Foundation

struct User: Codable {
    var firstName: String
    var lastName: String
}

let u1 = User(firstName: "Ann", lastName: "A")
let u2 = User(firstName: "Ben", lastName: "B")
let u3 = User(firstName: "Charlie", lastName: "C")
let u4 = User(firstName: "David", lastName: "D")

let a = [u1, u2, u3, u4]

var ret = [[String: Any]]()
for i in 0..<a.count {
        let param = [
            "a" : a[i],
            "b" : 45
            ] as [String : Any]
    ret.append(param)
}


let obj = ["obj": ret]

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(obj) // This line produces an error
print(String(data: data, encoding: .utf8)!)

What am I doing wrong?

Wavelet answered 23/3, 2018 at 23:50 Comment(1)
Possible duplicate: Any when decoding JSON with Codable?Optical
O
33

That message is misleading, the real error is that obj is of type [String: Any], which does not conform to Codable because Any does not.

When you think about it, Any can never conform to Codable. What will Swift use to store the JSON entity when it can be an integer, a string, or an object? You should define a proper struct to hold your data.

Olive answered 23/3, 2018 at 23:57 Comment(2)
Thanks. Is there a way to make [String : [String: Any]] codable?Wavelet
Any can never conform to Codable. You should define a proper struct to hold your dataOlive

© 2022 - 2024 — McMap. All rights reserved.