I am trying to return JSON data but I have no clue on how to do it. I get this error message "Cannot convert return expression of type '[Plant]' to return type 'Plant'". I sort of understand this error message, it means I can't convert one type to another type. But not sure how to solve this issue. Please see my code below:
import UIKit
import SwiftUI
struct PlantResponse: Codable {
let data : [Plant]
}
struct Plant: Codable {
let id: Int
let commonName: String // camelCase
let slug: String
let scientificName: String // camelCase
let year: Int
let bibliography: String
let author: String
let status: String
let rank: String
let familyCommonName: String // camelCase
let family: String
let genusId: Int // camelCase
let genus: String
let imageUrl: String // camelCase
let synonyms: [String] // an array of strings
let links: Links // a custom type, defined below
let Plant: [Plant]
}
extension Plant {
struct Links: Codable {
let `self`: String
let plant: String
let genus: String
}
}
struct ContentView: View {
@State var plant: Plant?
var body: some View {
VStack(alignment: .leading) {
if let plant {
Text("There is data")
.font(.title)
} else {
Text("No data available")
}
}
.padding(20.0)
.task {
do {
plant = try await fetchPlantsFromAPI()
} catch {
plant = nil
}
}
}
}
func fetchPlantsFromAPI() async throws -> Plant {
let url = URL(string: "https://trefle.io/api/v1/plants? token=d321f518jTdU1t-doZQif3jpzzW9V0mk3nLnDssF1vY&filter[common_name]=beach%20strawberry")!
do {
let (data, _) = try await URLSession.shared.data(from: url)
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let decoded = try! decoder.decode(PlantResponse.self, from: data)
print(decoded.data)
return decoded.data //Cannot convert return expression of type '[Plant]' to return type 'Plant'
} catch {
throw error
}
}
#Preview {
ContentView()
}
Any help would be appreciated.