Found the solution, but can't post the link here, below is the implementation, easy and clear:
@Model
class User {
var name: String
init(name: String) {
self.name = name
}
}
struct EditingView: View {
@Environment(\.modelContext) var modelContext
@Bindable var user: User
var body: some View {
Form {
TextField("Name", text: $user.name)
}
}
}
#Preview {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try! ModelContainer(for: User.self, configurations: config)
let user = User(name: "Test User")
return EditingView(user: user)
.modelContainer(container)
}
The core concept is, you must create the modelContainer first, then create the User, finally create the View pass the user in. Since a swift data model instance can not live without a model container
Topic:
Developer Tools & Services
SubTopic:
Xcode
Tags: