I am using the new SwiftUI to fetch Data from Web Api and Displaying Using SwiftUI and encounter and error and could not compile.
Error : Use of undeclared type BindableObject
*******ContentView.swift*********
import SwiftUI
struct ContentView: View {
@ObjectBinding var model = PostListViewModel()
var body: some View {
List(model.posts) { post in
Text(post.branchname)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
*******Post.swift*********
import Foundation
import SwiftUI
struct Post : Codable, Hashable, Identifiable {
//var id: ObjectIdentifier
let id : Int
let branchname : String
let aboutus : String
}
*******PostListViewModel.swift*********
import Foundation
import SwiftUI
import Combine
final class PostListViewModel: BindableObject {
init() {
fetchPosts()
}
var posts = [Post]() {
didSet {
didChange.send(self)
}
}
private func fetchPosts() {
Webservice().getAllPosts {
self.posts = $0
}
}
let didChange = PassthroughSubject<PostListViewModel,Never>()
}
Last I recall, BindableObject was renamed to ObservableObject and @ObjectBinding is now @ObservedObject. Additionally, in an ObservableObject you no longer need to implement didChange yourself, you just use the @Published attribute on any properties you want to publish and the rest will be taken care of for you.
struct ContentView: View {
@ObservedObject var model = PostListViewModel()
var body: some View {
List(model.posts) { post in
Text(post.branchname)
}
}
}
final class PostListViewModel: ObservableObject {
init() {
fetchPosts()
}
@Published var posts = [Post]()
private func fetchPosts() {
Webservice().getAllPosts {
self.posts = $0
}
}
}