我有以下课程
import SwiftUI
let apiUrl = "https://api.letsbuildthatapp.com/static/courses.json"
struct Course: Identifiable, Decodable {
let id = UUID()
let name: String
let price: Int
}
class CoursesViewModel: ObservableObject {
@Published var courses: [Course] = [
.init(name: "Course 1", price: 0),
.init(name: "Course 2", price: 0),
.init(name: "Course 3", price: 0)
]
func fetchCourses() {
guard let url = URL(string: apiUrl) else { return }
URLSession.shared.dataTask(with: url) { (data, resp, err) in
DispatchQueue.main.async {
do {
self.courses = try JSONDecoder().decode([Course].self, from: data!)
print("self.courses.count",self.courses.count)
} catch {
print("Failed to decode JSON:", error)
}
}
}.resume()
}
}
我有一个TableView,它应该呈现课程数据。通常,在不使用该协议的情况下,我进行提取,并在收到响应时更新其单元格。
如何重新加载表视图数据观察 课程变量的变化。