I’m going through the IOS networking course where the Environmen was introduced. To reinforce learning, I’m writing an app in parallel with taking the course.
On my example app that I am creating, InformationView.swift, line 24 provides the following error when I build the project:
Value of type ‘Bindable’ has no dynamic member ‘localContacts’ using key path from root type ‘EventModel’
Line 24 of InformationView.swift is as follows; " if $model.localContacts.count > 0 {"
I have been trying to figure this out for a few days, and was hoping someone might be able to point me in the right direction.
-Thank you
Here is the project (I have tried to remove most of the excess stuff for readability.)
-------Event.swift-------------
import Foundation
struct Event: Decodable {
var title: String
var subtitles: [String]?
var date: String
var localContacts: [ContactInfo]
}
struct ContactInfo: Identifiable, Decodable {
var id: Int
var name: String
}
-------EventModel.swift-------
import Foundation
import SwiftUI
@Observable
class EventModel {
var event = Event(title: "Event Loading",
subtitles: [""],
date: "",
localContacts: [ContactInfo(id: 0, name: "")]
)
func getEvents() {
event = Event(title: "Event Loading", subtitles: [""], date: "",
localContacts: [ContactInfo(id: 0, name: "local")])
}
}
-------ContentView.swift-------
import SwiftUI
struct ContentView: View {
@Environment(EventModel.self) var model
var body: some View {
@Bindable var model = model
VStack {
InformationView()
}
.onAppear() {
model.getEvents()
}
}
}
#Preview {
ContentView()
.environment(EventModel())
}
-------InformationView.swift-------
import SwiftUI
struct InformationView: View {
@Environment(EventModel.self) var model
var body: some View {
@Bindable var model = model
VStack {
Text("Information")
.font(.title)
.bold()
.padding(.top, 20)
ScrollView {
if $model.localContacts.count > 0 {
Text("Local Contacts")
.font(.title3)
.bold()
.padding()
ForEach ($model.localContacts) { person in
Text(person.name)
.font(.title2)
.bold()
}
}
}
}
}
}
#Preview {
InformationView()
.environment(EventModel())
}