Hello guys,
I trying to request some data from an API, decoded it and save the values into a @State variable in my View. I'm new with Swift, so I know that my explanation is wrong. It would be better if I show you my code:
Request function
Model data
JSON Response
View
The problem is, when I try to save the results into de @State var I get this error Cannot assign value of type 'QuoteModel to type QuoteModel.Type
When the JSON response is an array of JSON, for example
I do not get this error and it works perfectly. What am I missing?
Thank you.
Dennis.
I trying to request some data from an API, decoded it and save the values into a @State variable in my View. I'm new with Swift, so I know that my explanation is wrong. It would be better if I show you my code:
Request function
Code Block Swiftui // Request API func request<T: Decodable>(url: String, model: T.Type, completion: @escaping (T) -> Void) { // We take some model data T.Type guard let url = URL(string: url) else { print("Invalid URL") return } let request = URLRequest(url: url) URLSession.shared.dataTask(with: request) { data, response, error in if let data = data { do { // Decode response with the model passed let decodedResponse = try JSONDecoder().decode(model, from: data) DispatchQueue.main.async { print(decodedResponse) completion(decodedResponse) } return } catch { print(error) } } print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")") } .resume() }
Model data
Code Block Swiftui struct QuoteModel: Codable { var latestPrice: Float var changePercent: Double }
JSON Response
Code Block JSON { "latestPrice": 100.01, "changePercent": 0.02 }
View
Code Block Swiftui struct Price: View { @State var quote = QuoteModel.self var body: some View { Text("Hello world") .onAppear { request(url: endpoint, model: QuoteModel.self) { self.quote = $0 } } } }
The problem is, when I try to save the results into de @State var I get this error Cannot assign value of type 'QuoteModel to type QuoteModel.Type
When the JSON response is an array of JSON, for example
Code Block JSON [ { "latestPrice": 100.01, "changePercent": 0.02 }, { "latestPrice": 50.05, "changePercent": 0.003 } ]
I do not get this error and it works perfectly. What am I missing?
Thank you.
Dennis.