Hello :)
I am trying to decode a JSON stock market API then store the returned information in an instance of a struct but am getting Thread 1: signal SIGABRT on the struct instance line of code.
The JSON data is in an array of objects that would like this:
{
"pagination": {
... //Not interested in storing this info
},
"data": [
{
"open": 129.8,
"high": 133.04,
},
[...] //would be data for other symbols
]
}
Struct Declaration:
struct SingleData: Decodable {
let open: Double
let high: Double
}
struct ScrapeStruct: Decodable {
let data: [SingleData]
}
Struct Instance:
var QQQ = try ScrapeStruct(from: Decoder.self as! Decoder) //Thread 1: signal SIGABRT error
Target Output says "Could not cast value of type 'Swift.Decoder.Protocol' (0x1db05bc88) to 'Swift.Decoder'". I know that this is in reference to the .self but I tried other things like Decoder() and even SingleData() or ScrapeStruct(). But just got compiler errors about it not being initialized and that it's missing from: Decoder respectively. And with the struct containing an array and me having issues working with individual values like QQQ.high because ScrapeStruct has no member high I just have no idea what is supposed to be here.
I don't know if this part of the code is helpful but I will include it anyways just in case.
Function:
func Scraper() async throws -> ScrapeStruct {
guard let url = URL(string: "MarketStack API")
else {
throw Error.invalidServerResponse
}
var request = URLRequest(url: url)
request.addValue("My Access Code", forHTTPHeaderField: "access_key")
request.addValue("QQQ", forHTTPHeaderField: "symbols")
let (data, _) = try await URLSession.shared.data(for: request)
let scrapeStruct = try JSONDecoder().decode(ScrapeStruct.self, from: data)
return scrapeStruct
}
Call Function:
Task {
let fetchedInfo = try? await Scraper()
DispatchQueue.main.async {
if let fetched = fetchedInfo {
QQQ = fetched
}
}
}
Any help at all would be greatly appreciated. Thanks!