这里我有一个读取ObservedObject的文本字段的视图。观察对象有一个名为"用户"的属性。可选类型为"NewUser?"。当我试图打开&;newuser &;我得到一个错误,说我仍然必须打开它。
的错误分类列出模型struct NewUser: {
var id: UUID?
var username: String
}
观察对象class HTTPUserClient: ObservableObject {
@Published var user: NewUser? //a user struct with a non optional
//function and stuff ommitted
}
<<h3>视图/h3>import SwiftUI
struct TestUserEditor: View {
@ObservedObject var userClient:HTTPUserClient
var body: some View {
TextField("required", text: $userClient.user!.username)
}
}
的错误如果我使用上面的代码,我得到以下错误
Value of optional type 'NewUser?' must be unwrapped to refer to member 'firstName' of wrapped base type 'NewUser'
但是如果我通过添加"!"来修复它,强制展开用户,我得到相同的错误
我的建议是通过添加静态example
作为占位符来摆脱可选。
struct NewUser {
var id: UUID?
var username: String
static let example = NewUser(id: nil, username: "")
}
并声明user
@Published var user = NewUser.example