This is My Model.
public struct ResponseModel: Decodable {
public var userslists: [UserslistModel]
}
public struct UsersList:Decodable, Hashable {
public var id: Int
public var fullName: String
public var totalBooks: Int?
public var fullAddress: String?
public var logoUrl: String
private enum CodingKeys: String, CodingKey {
case id, totalBooks
case fullName = "full_name"
case fullAddress = "full_address"
case logoUrl = "logo_url"
}
}
This is My View Model
When I want to assign the results.userslists then show this Cannot assign value of type ‘[UserslistModel]’ to type ‘[UsersList]’
class UsersListViewModel: ObservableObject {
@Published var datas = [UsersList]()
let url = "https://www.alibrary.in/api/web-home"
init() {
getData(url: url)
}
func getData(url: String) {
guard let url = URL(string: url) else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
if let data = data {
do {
let results = try JSONDecoder().decode(ResponseModel.self, from: data)
DispatchQueue.main.async {
self.datas = results.userslists // here gives an error....
}
}
catch {
print(error)
}
}
}.resume()
} }
This is my View and I try to fetch the value of Api data
The error show in My View part that is No exact matches in call to instance method ‘appendInterpolation’
struct ExampleViewApi: View {
@ObservedObject var list = UsersListViewModel()
var body: some View{
ScrollView(.horizontal,showsIndicators: false){
HStack{
ForEach(list.datas, id: \.id){ item in
Text(item.fullAddress ?? "Anoop")
Text("\(item.totalBooks)") // Here show an error more ....
Text(item.fullName)
Text(item.logoUrl) // I want to show Url only
}
}
}
}
}
>Solution :
public struct ResponseModel: Decodable {
public var userslists: [UserslistModel]
}
public struct UsersList:Decodable, Hashable {
public var id: Int
public var fullName: String
public var totalBooks: Int?
public var fullAddress: String?
public var logoUrl: String
private enum CodingKeys: String, CodingKey {
case id, totalBooks
case fullName = "full_name"
case fullAddress = "full_address"
case logoUrl = "logo_url"
}
}
class UsersListViewModel: ObservableObject {
@Published var datas = [UsersList]()
let url = "https://www.alibrary.in/api/web-home"
init() {
getData(url: url)
}
func getData(url: String) {
guard let url = URL(string: url) else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
if let data = data {
do {
let results = try JSONDecoder().decode(ResponseModel.self, from: data)
DispatchQueue.main.async {
self.datas = results.userslists // here gives an error....
}
}
catch {
print(error)
}
}
}.resume()
} }
struct ExampleViewApi: View {
@ObservedObject var list = UsersListViewModel()
var body: some View{
ScrollView(.horizontal,showsIndicators: false){
HStack{
ForEach(list.datas, id: \.id){ item in
Text(item.fullAddress ?? "Anoop")
Text("\(item.totalBooks ?? 0)") // This is optional so ....
Text(item.fullName)
Text(item.logoUrl) // I want to show Url only
}
}
}
}
}