Having troubles getting this to work: I am trying to abstract the JSON-decoding into a function, taking as arguments a Codable plus some Data.
Therefore, I need to have the following function-signature if possible for this:
func doTheJSONDecoding(cdbl: Codable, data: Data) {...}
Here is my code, starting with the data-model. There are two examples below....
import UIKit
import Foundation
struct MyStructCodable : Codable {
let items : [MyValue]?
}
struct MyValue : Codable {
let value : String?
}
let dta: Data = """
{
"items": [
{
"value": "Hello1"
}
]
}
""".data(using: .utf8)!
Then the two examples:
// Example 1: this code works fine !!!!!!!!!!!!!!!!!!!!!!!!
let decoder = JSONDecoder()
do {
let result = try decoder.decode(MyStructCodable.self, from: dta)
print(result.items?[0].value ?? "")
} catch {
print(error)
}
// above code prints: Hello1
// Example 2: this code does not work - WHY ???????????????
func doTheJSONDecoding(cdbl: Codable, data: Data) {
let decoder = JSONDecoder()
do {
let result = try decoder.decode(cdbl, from: data)
print(result.items?[0].value ?? "")
} catch {
print(error)
}
}
let myValue = MyValue(value: "Hello2")
let myStructyCodable = MyStructCodable(items: [myValue])
doTheJSONEncoding(cdbl: myStructyCodable, data: dta)
The error thrown is inside the function, it says:
Is there any way so that I can keep the function signature (i.e. func doTheJSONDecoding(cdbl: Codable, data: Data)
and still getting this to work ?? Any help appreciated.