Reputation: 1271
I am trying to make a reusable JSON decoder in my Swift app, but am getting the following errors when running:
My code is below:
func decode<T: Codable>(_ type: T.Type, from: String) -> [T] {
let url = URL(fileURLWithPath: from)
let data = try? Data(contentsOf: url)
let result = try? JSONDecoder().decode([T].self, from: data!)
return result!
}
print(decode(User.self, from: "data.json")
Thank you for assisting me in solving this problem.
Best Regards, NG253
Upvotes: 1
Views: 4087
Reputation: 51872
You don't need to pass the type as an argument if the return type is known to the compiler
Here is my version (using a local string)
func decode<T: Decodable>(from: String) throws -> [T] {
//let url = URL(fileURLWithPath: from)
//let data = try? Data(contentsOf: url)
let data = from.data(using: .utf8)!
return try JSONDecoder().decode([T].self, from: data!)
}
struct User: Decodable {
let name: String
}
let str = """
[{"name": "abc"}]
"""
do {
let users: [User] = try decode(from: str)
} catch {
print(error)
}
Upvotes: 1