Hello, I am trying to code an API scraper that will collect Double values in a struct then return them but am getting the title error on the return line of code.
Struct Declaration:
struct ScrapeStruct: Decodable {
var high: Double
var low: Double
var close: Double
var volume: Double
}
Error Declaration:
enum Error: Error {
case invalidServerResponse
}
Scrape Function:
class dataFetcher {
func Scraper() async throws -> ScrapeStruct {
guard let url = URL(string: "someURL")
else {
throw Error.invalidServerResponse
}
let request = URLRequest(url: url)
let (data, _) = try await URLSession.shared.data(for: request)
_ = try JSONDecoder().decode(ScrapeStruct.self, from:data)
return ScrapeStruct.init(high: Double, low: Double, close: Double, volume: Double) // error is here
}
}
I am self-taught so there's a chance there are some fundamentel misunderstandings so if that's the case any recommendations on where to learn more in place of a solution are appreciated as well because I can't find anything online that's too helpful.
When you create the struct in
ScrapeStruct.init(high: Double, low: Double, close: Double, volume: Double)
you need to pass values for arguments, not their type (Double)
You should write:
let value = try JSONDecoder().decode(ScrapeStruct.self, from:data)
return ScrapeStruct.init(high: value.high, low: value.low, close: value.close, volume: value.volume)
But there is a much simpler way:
let value = try JSONDecoder().decode(ScrapeStruct.self, from:data)
return value
There are a lot of JSON tutorials.
This one is good: https://www.raywenderlich.com/3418439-encoding-and-decoding-in-swift