Swiftui-带有可选观察的Textfield
在这里,我的视图带有一个文本字段,该文字字段读取了一个观察到的对象。观察到的对象具有可选类型的“用户”的属性“ 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
}
查看
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'
,但是如果我通过添加“!”来修复它,则强制解开用户,我会得到相同的错误
Here I have view with a textfield that reads off an ObservedObject. The Observed object has a property called "user" that is of optional type "NewUser?". When I try to unwrap the "NewUser" to retrieve its username for the textfied I get an error saying that I must still unwrap it.
The Errors
NewUser Model
struct NewUser: {
var id: UUID?
var username: String
}
Observed Object
class HTTPUserClient: ObservableObject {
@Published var user: NewUser? //a user struct with a non optional
//function and stuff ommitted
}
View
import SwiftUI
struct TestUserEditor: View {
@ObservedObject var userClient:HTTPUserClient
var body: some View {
TextField("required", text: $userClient.user!.username)
}
}
The errors
IF I use the above code I get the following error
Value of optional type 'NewUser?' must be unwrapped to refer to member 'firstName' of wrapped base type 'NewUser'
but if I fix it by adding a "!", force unwrapping the user, I get the same error
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的建议是通过添加静态
示例
作为占位符来摆脱可选。并声明
用户
My suggestion is to get rid of the optional by adding a static
example
as a placeholder.and declare
user