在Xcode预览时,尝试初始化User类报错。
struct EditUserView: View {
@Bindable var user: User
var body: some View {
...
}
}
#Preview {
EditUserView(user: User())
}
这个报错的原因为User类是一个SwiftData模型类,因此默认初始化器会要求传递一个backingData参数。
@Model
class User {
var name: String
var city: String
var joinDate: Date
...
}
解决方案为,提供一个User实例,以及配置ModelConfiguration和ModelContainer:
#Preview {
do {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(for: User.self, configurations: config)
let user = User(name: "Taylor Swift", city: "Nashville", joinDate: .now)
return EditUserView(user: user)
.modelContainer(container)
} catch {
return Text("Failed to create container: \(error.localizedDescription)")
}
}